首页 > 其他 > 详细

LeetCode(18) - 4Sum

时间:2016-03-13 14:06:12      阅读:99      评论:0      收藏:0      [点我收藏+]

  思路和3Sum一样,只是把O(n^4)变成了O(n^3),思路详细见3sum。最终能够ac。

  代码如下:

 1 public class Solution {
 2     public List<List<Integer>> fourSum(int[] nums, int target) {
 3         List<List<Integer>> res = new ArrayList<List<Integer>>();
 4         //先排序
 5         Arrays.sort(nums);
 6         for (int i = 0; i < nums.length - 3; i++) {
 7             //判断重复
 8             if (i != 0 && nums[i] == nums[i - 1]) continue;
 9             for (int j = i + 1; j < nums.length - 2; j++) {
10                 //判断重复
11                 if (j != i + 1 && nums[j] == nums[j - 1]) continue;
12                 int head = j + 1;
13                 int tail = nums.length - 1;
14                 while (head < tail) {
15                     //判断重复
16                     if (head != j+1 && nums[head] == nums[head - 1]) {
17                         head++;
18                         continue;
19                     }
20                     int sum = nums[i] + nums[j] + nums[head] + nums[tail];
21                     if (sum > target) tail--;
22                     else if (sum < target) head++;
23                     else {
24                         List<Integer> list = new ArrayList<Integer>();
25                         list.add(nums[i]);
26                         list.add(nums[j]);
27                         list.add(nums[head++]);
28                         list.add(nums[tail--]);
29                         res.add(list);
30                     }
31                 }
32             }
33         }
34         return res;
35     }
36 }

 

LeetCode(18) - 4Sum

原文:http://www.cnblogs.com/kepuCS/p/5271682.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!