Last active
February 20, 2016 01:17
-
-
Save doyonghoon/a5749695c6daf2e551f6 to your computer and use it in GitHub Desktop.
Find two sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package problem; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
public class TwoSum { | |
public static void main(String[] args) { | |
List<int[]> array = new TwoSum().twoSum(new int[]{3, 4, 5, 6}, 5); | |
for (int[] arr : array) { | |
System.out.println(Arrays.toString(arr)); | |
} | |
} | |
public List<int[]> twoSum(int[] nums, int target) { | |
for (int i = 0; i < nums.length; i++) { | |
nums[i] *= nums[i]; | |
} | |
target *= target; | |
List<int[]> result = new ArrayList<>(); | |
Map<Integer, Integer> m = new HashMap<>(); | |
for (int i = 0; i < nums.length; i++) { | |
if (m.containsKey(nums[i])) { | |
int[] pair = new int[2]; | |
pair[0] = m.get(nums[i]) + 1; | |
pair[1] = i + 1; | |
result.add(pair); | |
} else { | |
m.put(target - nums[i], i); | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Input
Output
so the output will be
[1, 2]
because it showsindex + 1
of3
andindex + 1
of4
.