[leetcode]4Sum

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   strong   

4Sum

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.

 

    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.    A solution set is:    (-1,  0, 0, 1)    (-2, -1, 1, 2)    (-2,  0, 0, 2)

思路1:
與之前的[leetcode]3Sum類似,加一層外部迴圈,時間複雜度為O(n ^ 3)
代碼如下:
 1 public class Solution { 2     public List<List<Integer>> fourSum(int[] num, int target) { 3         List<List<Integer>> result = new ArrayList<List<Integer>>(); 4         if(num == null || num.length < 4) return result; 5         int length = num.length; 6         Arrays.sort(num); 7         for (int i = 0; i < length - 3; i++) { 8             if(i > 0 && num[i] == num[i - 1])continue; 9             int one = i;10             for (int j = i + 1; j < length - 2; j++) {11                 if(j > i + 1 && num[j] == num[j - 1])continue;12                 int two = j;13                 int three = j + 1;14                 int four = length - 1;15                 while (three < four) {16                     int sum = num[one] + num[two] + num[three] + num[four];17                     if(sum < target) three++;18                     else if(sum > target) four--;19                     else{20                         List<Integer> list = new ArrayList<Integer>();21                         list.add(num[one]);22                         list.add(num[two]);23                         list.add(num[three]);24                         list.add(num[four]);25                         result.add(list);26                         three++;27                         four--;28                     while(three < four && num[three] == num[three-1]) three++;29                         while(three < four &&num[four] == num[four+1]) four--;30                     }31                 }32             }33         }34         return result;35     }36 }

【吐槽】第一次做這道題的時候,怎麼也想不到O(n ^ 3)居然能過,絞盡乳汁【(⊙o⊙)好邪惡】想怎麼才能把時間複雜度壓縮到O(n ^ 2),我相信面試的時候要求肯定也是O(n^2),因此查了網上的一些大神的思路,對本題做了進一步的最佳化

思路2:

1. 計算出數組中兩兩元素的和,把這種二度元素成為nodeOfTwo(學過排列組合的話,應該可以想象到這個數有多大,沒辦法,空間換時間吧)

2. 對每一個nodeOfTwo元素進行遍曆,類似於求[leetcode]Two Sum

2.1 如果存在兩個nodeOfTwo元素的和為target,即找到了滿足條件的四個元素。

2.2 nodeOfTwo的value毫無疑問是一個list

疑問:

1. 如何去除相同元素?對於nodeOfTwo - 3【何為3的元素對組合】中可能包含兩對或以上(0,3)

2. 如何去除重複元素?對於不同的nodeOfTwo節點的組合,還可能有重複,例如nodeOfTwo - 1 和nodeOfTwo - 4包含一個組合(0,1,1,3)但是nodeOfTwo - 3 和nodeOfTwo - 2 中可能包含(0,3,1,1)事實上是重複元素。

代碼如下:

 

 1 public List<List<Integer>> fourSum(int[] num, int target) { 2         List<List<Integer>> result = new ArrayList<List<Integer>>(); 3         if(num == null || num.length < 4) return result; 4         int length = num.length; 5         Arrays.sort(num); 6         Map<Integer,List<int[]>> hash = new HashMap<Integer,List<int[]>>(); 7         for(int i = 0; i < length - 1;i++){ 8             for(int j = i + 1; j < length; j++){ 9                 int sum = num[i] + num[j];10                 if(hash.get(sum) == null){11                     List<int[]> list = new ArrayList<int[]>();12                     list.add(new int[]{i,j});13                     hash.put(sum, list);14                 }else{15                     hash.get(sum).add(new int[]{i,j});16                 }17             }18         }19         for(int nodeOfTwo : hash.keySet()){20             if(hash.containsKey(target - nodeOfTwo)){21                 for(int[] oneAndTwo : hash.get(nodeOfTwo)){22                     for(int[] threeAndFour : hash.get(target - nodeOfTwo)){23                         if(oneAndTwo[0] == threeAndFour[0] || oneAndTwo[0] == threeAndFour[1] || oneAndTwo[1] == threeAndFour[0] || oneAndTwo[1] == threeAndFour[1] )continue;//去除重複元素24                         int[] node = {num[oneAndTwo[0]],num[oneAndTwo[1]],num[threeAndFour[0]],num[threeAndFour[1]]};25                         Arrays.sort(node);26                         boolean exist = false;27                         for(List<Integer> tem : result){//去除相同元素28                             int count = 0;29                             for(int i = 0; i < 4; i++){30                                 if(node[i] == tem.get(i))count++;31                             }32                             if(count == 4) exist = true;33                         }34                         if(!exist) {35                             List<Integer> list = new ArrayList<Integer>();36                             for(int i = 0; i < 4; list.add(node[i++]));37                             result.add(list);38                         }39                     }40                 }41             }42         }43         return result;44     }

【吐槽】代碼還是太醜了,哎,不過與之前的相比還是稍微好點的,謹慎點擊->[leetcode]4Sum

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.