Skip to content

Instantly share code, notes, and snippets.

@doyonghoon
Last active February 20, 2016 01:17
Show Gist options
  • Save doyonghoon/a5749695c6daf2e551f6 to your computer and use it in GitHub Desktop.
Save doyonghoon/a5749695c6daf2e551f6 to your computer and use it in GitHub Desktop.
Find two sum
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;
}
}
@doyonghoon
Copy link
Author

Input

new int[]{3, 4, 5, 6}, 5

Output

[1, 2]

so the output will be [1, 2] because it shows index + 1 of 3 and index + 1 of 4.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment