forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum.java
More file actions
45 lines (37 loc) · 1.25 KB
/
3Sum.java
File metadata and controls
45 lines (37 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> set = new HashSet<>();
Arrays.sort(nums);
for (int i=0; i<nums.length; i++) {
for (int j=i+1; j<nums.length; j++) {
int target = -1 * (nums[i] + nums[j]);
int idx = findBinary(nums, j+1, nums.length-1, target);
if (idx != -1) {
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[idx]);
set.add(temp);
}
}
}
List<List<Integer>> ans = new ArrayList<>();
ans.addAll(set);
return ans;
}
private int findBinary(int[] nums, int start, int end, int target) {
while (start <= end) {
int mid = (start + end)/2;
if(nums[mid] == target) {
return mid;
}
else if (nums[mid] > target) {
end = mid-1;
}
else {
start = mid + 1;
}
}
return -1;
}
}