题解 | #四数之和#
四数之和
https://www.nowcoder.com/practice/d5b74806fa104518903884e182f47e35
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型vector * @param target int整型 * @return int整型vector<vector<>> */ vector<vector<int> > fournumber(vector<int>& nums, int target) { // write code here vector<vector<int>> tmp; sort(nums.begin(),nums.end()); int n = nums.size(); for(int i = 0;i<n;) { //固定第一个数 int p1 = nums[i]; for(int j = i+1;j< n-1;) { int p2 = nums[j]; int left = j+1; int right = n-1; while(left < right) { if(nums[left] + nums[right] > ((long long)target - p1 -p2)) --right; else if(nums[left] + nums[right] < ((long long)target - p1 -p2)) ++left; else { tmp.push_back({p1,p2,nums[left],nums[right]}); ++left,--right;//保证遍历充分 while(left < right && nums[left] == nums[left-1]) ++left;//去重操作 while(right > left && nums[right] == nums[right+1]) --right; } } j++; while(j < n-1 && nums[j] == nums[j-1]) ++j; } i++; while(i<n && nums[i] == nums[i-1]) ++i; } return tmp; } };