标签:color style return div nts logs i++ cat length
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] ]
1 public List<List<Integer>> threeSum(int[] nums) { 2 Arrays.sort(nums); 3 List<List<Integer>> res = new LinkedList<>(); 4 for (int i = 0; i < nums.length; i++) { 5 if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) { 6 int low = i + 1, high = nums.length - 1; 7 while (low < high) { 8 if (nums[i] + nums[low] + nums[high] == 0) { 9 res.add(Arrays.asList(nums[i], nums[low], nums[high])); 10 while (low < high && nums[low] == nums[low + 1]) low++; 11 while (low < high && nums[high] == nums[high - 1]) high--; 12 low++; 13 high--; 14 } else if (nums[i] + nums[low] + nums[high] > 0) high--; 15 else low++; 16 } 17 } 18 } 19 return res; 20 }
标签:color style return div nts logs i++ cat length
原文地址:http://www.cnblogs.com/wzj4858/p/7675381.html