LeetCode 15. 3Sum
Description
Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0
? Find all unique triplets in the array which gives the sum of zero.
Example
Code
- java
import java.util.ArrayList;
class Solution {
public int binarySearch(int[] arr, int left, int right, int x) {
while(left < right) {
int mid = (left+right)/2;
if(arr[mid] == x) {
return mid;
} else if(arr[mid] > x) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Set<List<Integer>> set = new TreeSet<>();
int len = nums.length;
Arrays.sort(nums);
for(int st = 0; st < len-1; st++) {
for(int ed = len-1; ed > st; ed--) {
if(ed != len-1 && nums[ed] == nums[ed+1]) continue;
int diff = -(nums[st] + nums[ed]);
int mid = binarySearch(nums, st+1, ed-1, diff);
if(mid != st && mid != ed && nums[mid] == diff) {
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(nums[st]);
temp.add(nums[mid]);
temp.add(nums[ed]);
if(!result.contains(temp)) {
result.add(temp);
}
}
}
}
return result;
}
}
- Others’ solution
- Time complexity O(N^2)
import java.util.LinkedList;
class Solution {
public List<List<Integer>> threeSum(int[] num) {
Arrays.sort(num);
List<List<Integer>> res = new LinkedList<>();
for (int i = 0; i < num.length-2; i++) {
if (i == 0 || (i > 0 && num[i] != num[i-1])) {
int lo = i+1, hi = num.length-1, sum = 0 - num[i];
while (lo < hi) {
if (num[lo] + num[hi] == sum) {
res.add(Arrays.asList(num[i], num[lo], num[hi]));
while (lo < hi && num[lo] == num[lo+1]) lo++;
while (lo < hi && num[hi] == num[hi-1]) hi--;
lo++; hi--;
} else if (num[lo] + num[hi] < sum) lo++;
else hi--;
}
}
}
return res;
}
}
Conclusion
- 自己想复杂了,用一个循环遍历数组后,就转化为2Sum问题,然后就可以用two-pointer思想,菜是原罪(所以一定要先想清楚再code!)
- 数组中的其他元素可以多次利用
- 去重