标签:需要 第一个 algo 等于 sam integer 算法题目 倒数 each
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] ]
Java Solution:
Runtime beats 82.41%
完成日期:07/11/2017
关键词:Array
关键点:利用TwoSum(two pointers)来辅助
1 public class Solution 2 { 3 public List<List<Integer>> threeSum(int[] nums) 4 { 5 Arrays.sort(nums); 6 List<List<Integer>> res = new ArrayList<>(); 7 8 for(int i=0; i<nums.length-2; i++) // no need to find twoSum if rest array size is only 1 or 0 9 { 10 if(i > 0 && nums[i] == nums[i-1]) // if previous num is same, skip this num 11 continue; 12 13 // for each num, find the twoSum which equal -num in the rest array 14 int left = i + 1; 15 int right = nums.length-1; 16 int sum = nums[i] * -1; 17 18 while(left < right) 19 { 20 if(nums[left] + nums[right] == sum) // find the two 21 { 22 res.add(Arrays.asList(nums[i], nums[left], nums[right])); // ascending order 23 left++; 24 right--; 25 26 while(left < right && nums[left] == nums[left-1]) // if next num is same as this, skip this 27 left++; 28 while(left < right && nums[right] == nums[right+1]) 29 right--; 30 } 31 else if(nums[left] + nums[right] > sum) // meaning need smaller sum 32 right--; 33 else // nums[left] + nums[right] < sum, meaning need larger sum 34 left++; 35 } 36 37 } 38 39 return res; 40 } 41 }
参考资料:
https://discuss.leetcode.com/topic/8125/concise-o-n-2-java-solution
LeetCode 算法题目列表 - LeetCode Algorithms Questions List
标签:需要 第一个 algo 等于 sam integer 算法题目 倒数 each
原文地址:http://www.cnblogs.com/jimmycheng/p/7153565.html