首页 > 其他 > 详细

4Sum

时间:2014-02-13 14:51:05      阅读:391      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
 1 public class Solution {
 2     public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
 3         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
 4         int len = num.length;
 5         if(len<=3) return res;
 6         Arrays.sort(num);
 7         for(int i=0;i<=len-4;i++){
 8             for(int j=i+1;j<=len-3;j++){
 9                 int sum = target - num[j]-num[i];
10                 int start = j+1;
11                 int end = len-1;
12                 while(start<end){
13                     if(num[start]+num[end]==sum){
14                         ArrayList<Integer> temp = new ArrayList<Integer>();
15                         temp.add(num[i]);
16                         temp.add(num[j]);
17                         temp.add(num[start]);
18                         temp.add(num[end]);
19                         res.add(temp);
20                         start++;
21                         end--;
22                         while(start<end && num[start]==num[start-1]){
23                             start++;
24                         }
25                         while(start<end && num[end]==num[end+1]){
26                             end--;
27                         }
28                     }
29                     else if(num[start]+num[end]>sum){
30                         end--;
31                     }
32                     else{
33                         start++;
34                     }
35                 }
36                 while(j<len-3 &&num[j]==num[j+1]){
37                         j++;
38                 }
39             }
40             while(i<len-4 &&num[i]==num[i+1]){
41                 i++;
42             }
43         }
44         return res;
45     }
46 }
View Code

4Sum

原文:http://www.cnblogs.com/krunning/p/3547426.html

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