File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ /* *
4+ * AC:
5+ * Runtime: 48 ms, faster than 30.52% of C++ online submissions for 4Sum.
6+ * Memory Usage: 10.6 MB, less than 11.68% of C++ online submissions for 4Sum.
7+ *
8+ * 思路:先排序,然后以 O(n^2) 的复杂度做遍历,每一轮用两个游标缩小范围。
9+ * 总体复杂度:O(n^2)
10+ */
11+ vector<vector<int >> fourSum (vector<int >& nums, int target) {
12+ vector<vector<int > >ret;
13+ int size = nums.size ();
14+ if (size < 4 )
15+ return vector<vector<int > >();
16+
17+ // sort
18+ sort (nums.begin (), nums.end ());
19+
20+ for (int i = 0 ; i < size - 1 ; i++) {
21+ for (int j = i + 1 ; j < size; j++) {
22+ int l = j + 1 ;
23+ int r = size - 1 ;
24+ while (l < r) {
25+ int tempSum = nums[i] + nums[j] + nums[l] + nums[r];
26+ if (tempSum == target) {
27+ vector<int >tempArr;
28+ tempArr.push_back (nums[i]);
29+ tempArr.push_back (nums[j]);
30+ tempArr.push_back (nums[l]);
31+ tempArr.push_back (nums[r]);
32+
33+ int flag = 0 ;
34+ for (auto it:ret) {
35+ if (it == tempArr) {
36+ flag = 1 ;
37+ break ;
38+ }
39+ }
40+ if (flag) {
41+ l++;
42+ continue ;
43+ }
44+
45+ ret.push_back (tempArr);
46+ // break; // 这里不应该直接退出,因为第三四个有可能有多种满足的组合
47+ l++;
48+ } else if (tempSum > target)
49+ r--;
50+ else if (tempSum < target)
51+ l++;
52+ }
53+ }
54+ }
55+
56+ return ret;
57+ }
58+ };
You can’t perform that action at this time.
0 commit comments