LeetCode18:四數之和
阿新 • • 發佈:2020-12-10
技術標籤:我的leetcode刷題指標leetcode資料結構
一、題目描述
給定一個包含 n 個整數的陣列 nums 和一個目標值 target,判斷 nums 中是否存在四個元素 a,b,c 和 d ,使得 a + b + c + d 的值與 target 相等?找出所有滿足條件且不重複的四元組。
注意:答案中不可以包含重複的四元組。
示例:給定陣列 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
滿足要求的四元組集合為:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
class Solution {
public :
vector<vector<int>> fourSum(vector<int>& nums, int target) {
//此處碼字
}
};
二、解題思路
本題與三數之和的題目差不多,可以先給容器內數字排序,然後迴圈枚舉出所有滿足條件的四元組,四元組的下標從小到大記為first,second,third,four。
為避免四元組重複,則有first<second<third<four;且若是nums[first/second/third]=nums[first/second/third-1],則直接跳過。
使用雙指標法,first與second的雙重迴圈內,有
four=n-1(n為vector的元素個數);
通過判斷nums[third]+nums[four]與newtarget來決定third(左指標)與four(右指標)如何移動:
1.如果和等於 target,則將列舉到的四個數加到答案中,然後將左指標右移直到遇到不同的數
2.如果和小於target,則將左指標右移一位;
3.如果和大於target,則將右指標左移一位。
三、我的程式碼
我在Visio studio上寫的,拷貝到力扣可以通過測試。
#include<iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> fourSum(vector<int>& nums, int target)
{
int n = nums.size();
sort(nums.begin(), nums.end());
vector<vector<int>>ans;
// 列舉 a
for(int first = 0; first < n; ++first) {
// 需要和上一次列舉的數不相同
if(first > 0 && nums[first] == nums[first - 1]) {
continue;
}
for(int second = first + 1; second < n;++second) {
// 需要和上一次列舉的數不相同
if(second > first + 1 && nums[second] == nums[second - 1]) {
continue;
}
int newtarget = target - nums[first] - nums[second];
int four = n - 1;
for (int third = second + 1; third < n; ++third) {
if (third >second + 1 && nums[third] == nums[third - 1]) {
continue;
}
while (third<four && nums[four] + nums[third]>newtarget) {
--four;
}
if (third == four) {
break;
}
if (nums[four] + nums[third] == newtarget) {
ans.push_back({nums[first],nums[second],nums[third] ,nums[four]});
}
}
}
}
return ans;
}
int main()
{
int target = 0;
vector<int>nums = { 1, 0, -1, 0, -2, 2 };
vector<vector<int>> result= fourSum(nums, target);
int n = result.size();
for (int i = 0; i < n; i++)
cout << result[i][0] << ' '
<< result[i][1] << ' '
<< result[i][2] << ' '
<< result[i][3] << ' '
<< endl;
return 0;
}
此例結果