15.3sum

題目連接:https://leetcode.com/problems/3sum/description/html

題目大意:與第一題相似,這個題是要求三數之和等於0,且結果不能重複。數組

解法一:兩層for循環,先排序,拿出一個數,對剩餘的數組進行第一題相似的兩數求和操做,方法能夠照搬第一題,能夠用兩指針移動,也能夠用hash表。這裏用的兩指針移動。還有要注意的點是要剪枝去除重複值。代碼以下(耗時73ms):ide

 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
相關文章
相關標籤/搜索