标签:ack pre target integer 排序 i++ lan 左右 TE
原题网址:https://www.lintcode.com/problem/4sum/description
给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。
四元组(a, b, c, d)中,需要满足a <= b <= c <= d
答案中不可以包含重复的四元组。
例如,对于给定的整数数组S=[1, 0, -1, 0, -2, 2] 和 target=0. 满足要求的四元组集合为:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
class Solution { public: /** * @param numbers: Give an array * @param target: An integer * @return: Find all unique quadruplets in the array which gives the sum of zero */ vector<vector<int>> fourSum(vector<int> &numbers, int target) { // write your code here vector<vector<int>> result; int n=numbers.size(); sort(numbers.begin(),numbers.end()); for (int i=0;i<n;i++) { if (i>0&&numbers[i]==numbers[i-1]) { continue; } for (int j=i+1;j<n;j++) { if (j>i+1&&numbers[j]==numbers[j-1]) { continue; } int left=j+1,right=n-1; while(left<right) { if (left>j+1&&numbers[left]==numbers[left-1]) { left++; continue; } if (right<n-1&&numbers[right]==numbers[right+1]) { right--; continue; } int sum=numbers[i]+numbers[j]+numbers[left]+numbers[right]; if (sum==target) { vector<int> temp(4,numbers[i]); temp[1]=numbers[j]; temp[2]=numbers[left]; temp[3]=numbers[right]; result.push_back(temp); left++; right--; } else if (sum<target) { left++; } else { right--; } } } } return result; } };
标签:ack pre target integer 排序 i++ lan 左右 TE
原文地址:https://www.cnblogs.com/Tang-tangt/p/9121299.html