# [18. 4Sum](https://leetcode.com/problems/4sum/) # 思路 和[3sum](https://github.com/ShusenTang/LeetCode/blob/master/15.%203Sum.md)这题基本一样的,注意这题由于循环层数比较多所以如果能 在外层循环判断一下的话可以提前终止循环或跳过某次循环,见代码。 时间复杂度O(n^3) # C++ ``` C++ class Solution { public: vector> fourSum(vector& nums, int target) { vector>res; int len = nums.size(), low, high, sum; if(len < 4) return res; sort(nums.begin(), nums.end()); for(int i = 0; i < len - 3; i++){ if(i != 0 && nums[i] == nums[i - 1]) continue; // 提前退出或跳过不可能的情况 if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3] > target) break; // 最小的都比target大了,可以提前终止循环 if(nums[i]+nums[len-3]+nums[len-2]+nums[len-1] < target) continue; for(int j = i + 1; j < len - 2; j++){ if(j != i + 1 && nums[j] == nums[j - 1]) continue; low = j + 1; high = len - 1; while(low < high){ sum = nums[i] + nums[j] + nums[low] + nums[high]; if(sum < target) while(++low < high && nums[low] == nums[low - 1]) ; // 不断右移low指针 else if(sum > target) while(low < --high && nums[high] == nums[high + 1]) ; // 不断左移high指针 else{ vectortmp = {nums[i], nums[j], nums[low++], nums[high--]}; res.push_back(tmp); while(low < high && nums[low] == nums[low - 1]) low++; while(low < high && nums[high] == nums[high + 1]) high--; } } } } return res; } }; ```