15. 3Sum(3 ptr)
medium
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
思路:Answer in the form of [..,i,j→ ,...,←k]
outer: i for loop (0 - len-2) and skip duplicates
inner: j = i+1, k= len-1 (while j<k), when sum equals 0, add results and skip dup
Complexity: O(n^2)
public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<>(); if(nums.length <= 2)return res; Arrays.sort(nums); for(int i = 0; i < nums.length - 2; i++){ if(i > 0 && nums[i-1] == nums[i])continue;//skip dup int j = i + 1, k = nums.length - 1;//[..,i,j->, ..., <-k] while(j < k){ int sum = nums[i] + nums[j] + nums[k]; if(sum == 0){ res.add(Arrays.asList(nums[i],nums[j],nums[k])); j++; k--; while(j < k && nums[j-1] == nums[j])j++;//skip duo while(j < k && nums[k+1] == nums[k])k--;//skip dup }else if(sum < 0){ j++; }else{ k--; } } } return res; }
No comments:
Post a Comment