演算法4Sum

dongyu2013發表於2014-05-04
 fourSum: 

Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ? b ? c ? d)
  • The solution set must not contain duplicate quadruplets.
再多兩層迴圈,此時已經是n立方的時間效率了,嘗試了一下,居然也AC了。不知道還有沒有更高效的演算法。
[java] view plaincopy
  1. import java.util.ArrayList;  
  2. import java.util.Arrays;  
  3.   
  4. public class FourSum {  
  5.     private ArrayList> list;  
  6.       
  7.     public ArrayList> fourSum(int[] num, int target) {  
  8.         list = new ArrayList>();  
  9.         Arrays.sort(num);  
  10.           
  11.         int i = 0;  
  12.         int j = 0;  
  13.         for (i = 0; i <= num.length - 4; i++) {  
  14.             if (i != 0 && num[i] == num[i - 1]) {  
  15.                 continue;  
  16.             }  
  17.               
  18.             for (j = i + 1; j <= num.length - 3; j++) {  
  19.                 if (j != i + 1 && num[j] == num[j - 1]) {  
  20.                     continue;  
  21.                 }  
  22.                 judgeAndPut(num, i, j, j + 1, num.length - 1, target);  
  23.             }  
  24.               
  25.         }  
  26.          
  27.         return list;              
  28.     }  
  29.   
  30.     private void judgeAndPut(int[] num, int i, int j, int p, int q, int target) {  
  31.         while (p 
  32.             int sum = num[i] + num[j] + num[p] + num[q];  
  33.             if (sum 
  34.                 p++;  
  35.             } else if (sum > target){  
  36.                 q--;  
  37.             } else if (sum == target) {  
  38.                 ArrayList tmpList = new ArrayList();  
  39.                 tmpList.add(num[i]);  
  40.                 tmpList.add(num[j]);  
  41.                 tmpList.add(num[p]);  
  42.                 tmpList.add(num[q]);  
  43.                 list.add(tmpList);  
  44.                 p++;  
  45.                 q--;  
  46.                 while (p 1]) {  
  47.                     p++;  
  48.                 }  
  49.                 while (p 1]) {  
  50.                     q--;  
  51.                 }  
  52.             }  
  53.         }  
  54.           
  55.     }  
  56.       
  57.     public static void main(String[] args) {  
  58.         int num[] = {-1,0,1,0,-2,2};  
  59.         System.out.println(new FourSum().fourSum(num, 0));  
  60.   
  61.     }  
  62.   
  63. }  

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29012686/viewspace-1153203/,如需轉載,請註明出處,否則將追究法律責任。

相關文章