LeetCode_4Sum,leetcode
一.題目4Sum Total Accepted: 29675 Total Submissions: 138870My Submissions
Given an array S of n integers, are there elements a, b, c, 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)
Show TagsHave you met this question in a real interview? Yes No
Discuss
二.解題技巧 這道題可以採用和3Sum一樣的思路,相同的方法,不過時間複雜度為O(n^3),空間複雜度為O(1)。 這道題也可以在排序之後先計算後面兩個數的和,將其方法一個雜湊表中,由於可能存在不同的兩個數的和為相同值,因此,可以考慮將和為相同的值放在一個鏈表中,然後將變數頭放在雜湊表中。然後再按照3Sum的思路,不過第三個數在這裡變成了第三個和第四個數的和,通過雜湊表可以方便地找到和為固定值的數的鏈表,就可以找到合格四個數。這種方法的時間複雜度為O(n^2),空間複雜度也為O(n^2)。(第二種方法我還沒實現)
三.實現代碼
class Solution{public: vector<vector<int> > fourSum(vector<int> &num, int target) { vector<vector<int> > Result; int Size = num.size(); if (Size < 4) { return Result; } // sort the array sort(num.begin(), num.end()); for (int Index_first = 0; Index_first < (Size - 3); Index_first++) { int First = num[Index_first]; if ((Index_first != 0) && (num[Index_first - 1] == num[Index_first])) { continue; } for (int Index_second = Index_first + 1; Index_second < (Size - 2); Index_second++) { if ((Index_second != (Index_first + 1)) && (num[Index_second - 1] == num[Index_second])) { continue; } int Second = num[Index_second]; int Index_third = Index_second + 1; int Index_foud = Size - 1; while (Index_third < Index_foud) { int Third = num[Index_third]; int Fourd = num[Index_foud]; int Sum = First + Second + Third + Fourd; if (Sum == target) { vector<int> Tmp; Tmp.push_back(First); Tmp.push_back(Second); Tmp.push_back(Third); Tmp.push_back(Fourd); Result.push_back(Tmp); Index_third++; while ((Index_third <= (Size - 1)) && (num[Index_third] == num[Index_third - 1])) { Index_third++; } Index_foud--; while ((Index_foud > Index_second) && (num[Index_foud] == num[Index_foud + 1])) { Index_foud--; } } if (Sum < target) { Index_third++; while ((Index_third < Size) && (num[Index_third] == num[Index_third - 1])) { Index_third++; } } if (Sum > target) { Index_foud--; while ((Index_foud > Index_second) && (num[Index_foud] == num[Index_foud + 1])) { Index_foud--; } } } } } return Result; }};
四.體會 這道題是3Sum的一種延伸,不過如果僅僅按照3Sum的延伸來做這道題的話,演算法的空間複雜度會達到O(n^3),但是空間複雜度為O(1)。可以換一種思路,在排序之後,先計算後面兩個數的和,並用雜湊表儲存起來,然後就將問題轉變為了3Ssum的問題,只不過計算出第三個數之後,還需要在雜湊表中找到和滿足條件的第三個數和第四個數。轉化一種思路就可以大大地降低計算複雜度,這個就是思路演算法的樂趣所在。
著作權,歡迎轉載,轉載請註明出處,謝謝