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:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- 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)
把数组从0到length - 3 进行遍历 , nums[i]为第一个数 从i + 1 到len -1 用2sum的双指针方法查找 找到一个解之后挪动指针继续查找
要注意数组中的重复问题
遍历的复杂度是O(n) 双指针查找的复杂度是O(n) 所以时间复杂度O(n^2)
public class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if (nums.length < 3 || nums == null) { return res; } Arrays.sort(nums); for (int i = 0; i < nums.length - 2; i++) { if (i > 0 && nums[i] == nums[i - 1]) {//防止出现重复 continue; } int left = i + 1; int right = nums.length - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum > 0) { right--; } else if (sum < 0) { left++; } else { List<Integer> tem = new ArrayList<Integer>(); tem.add(nums[i]); tem.add(nums[left]); tem.add(nums[right]); res.add(tem); left++; right--; while (left < right && nums[left] == nums[left - 1]) { left++;//防止数组出现重复 } while (left < right && nums[right] == nums[right + 1]) { right--; } } } } return res; } }
没有评论:
发表评论