Skip to content

Commit 0f3d16c

Browse files
MEDIUM/src/medium/_3Sum.java
1 parent 1fd7d00 commit 0f3d16c

File tree

1 file changed

+24
-17
lines changed

1 file changed

+24
-17
lines changed

MEDIUM/src/medium/_3Sum.java

+24-17
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,34 @@
55
import java.util.List;
66

77
public class _3Sum {
8-
8+
/**This solution is pretty clear and similar to my own thought:
9+
* https://discuss.leetcode.com/topic/26050/simple-o-n-2-two-pointers-java-solution*/
10+
11+
/**ATTN: this two-pointer technique here doesn't need a middle pointer!!! Instead, we just increment/decrement left
12+
* or right pointer by 1 each time when the sum != 0*/
913
public List<List<Integer>> threeSum(int[] nums) {
10-
Arrays.sort(nums);
1114
List<List<Integer>> result = new ArrayList();
12-
int left = 0, right = nums.length-1, mid = 0;
13-
while(left+1 < right){
14-
mid = left + (right-left)/2;
15-
int sum = nums[left] + nums[mid] + nums[right];
16-
if(sum == 0){
17-
List<Integer> list = new ArrayList();
18-
list.add(nums[left]);
19-
list.add(nums[mid]);
20-
list.add(nums[right]);
21-
22-
//move left forward to get all possible combinations
23-
} else if(sum > 0){
24-
right = mid;
25-
} else {
26-
left = mid;
15+
if(nums == null || nums.length == 0) return result;
16+
Arrays.sort(nums);//you'll have to sort it first, this is very important and very natural to think of
17+
for(int i = 0; i < nums.length; i++){//we can let i reach the last element, it's fine since we have other checks afterwards, it won't go out of bound exception.
18+
if(i >= 1 && nums[i] == nums[i-1]) continue;//skip equal elements to avoid duplicates
19+
int left = i+1, right = nums.length-1;
20+
while(left < right){
21+
int sum = nums[i] + nums[left] + nums[right];
22+
if(sum == 0){
23+
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
24+
while(left +1 < right && nums[left] == nums[left+1]) left++;
25+
while(right -1 > left && nums[right] == nums[right-1]) right--;
26+
left++;//be sure to have these two lines after the above two while loops
27+
right--;
28+
} else if(sum < 0){
29+
left++;
30+
} else {
31+
right--;
32+
}
2733
}
2834
}
35+
return result;
2936
}
3037

3138
}

0 commit comments

Comments
 (0)