首页 > 技术文章 > 15.3sum

cing 2018-01-05 20:39 原文

题目链接:https://leetcode.com/problems/3sum/description/

题目大意:与第一题类似,这个题是要求三数之和等于0,且结果不能重复。

解法一:两层for循环,先排序,拿出一个数,对剩余的数组进行第一题类似的两数求和操作,方法可以照搬第一题,可以用两指针移动,也可以用hash表。这里用的两指针移动。还有要注意的点是要剪枝去除重复值。代码如下(耗时73ms):

 1     public List<List<Integer>> threeSum(int[] nums) {
 2         int cnt = 0;
 3         //排序
 4         Arrays.sort(nums);
 5         int low = 0, high = 0, length = nums.length;
 6         List<List<Integer>> res = new ArrayList<List<Integer>>();
 7         for(int i = 0; i < length - 2; i++) {
 8             //因为不能有重复结果,如果第一个数值相同,剪枝
 9             if(i != 0 && nums[i] == nums[i - 1]) {
10                 continue;
11             }
12             for(low = i + 1, high = length - 1; low < high; ) {
13                 cnt = nums[low] + nums[high] + nums[i];
14                 if(cnt > 0) {
15                     high--;
16                 }
17                 else if(cnt < 0) {
18                     low++;
19                 }
20                 else {
21                     List<Integer> listIn = new ArrayList<Integer>();
22                     listIn.add(nums[i]);
23                     listIn.add(nums[low]);
24                     listIn.add(nums[high]);
25                     res.add(listIn);
26                     //剪枝,跳过重复数值
27                     while(low < high && nums[low] == nums[low + 1]) {
28                         low++;
29                     }
30                     while(low < high && nums[high] == nums[high - 1]) {
31                         high--;
32                     }
33                     low++;
34                     high--;
35                 }
36             }
37         }
38         return res;
39     }
View Code

 

推荐阅读