题目链接https://leetcode.cn/problems/3sum/description/
首先三层for暴力的话会超时,不可取!
根据两个的启发,这个要是个有序的就好了,同时可能含有多组答案
1.用指针,首先确定一个,下面两个在后面的数组内找,相当于两数和,python中有一个sort函数可以用!
2.二分法,首先要有序,先确定一个,然后以他之后的数组作为新数组再进行同样的操作此时新数组target=target-numbers[i],最终得到,三个
试一试!
我写的是一坨,又看了灵神的代码
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
a = []
n = len(nums)
for i in range(n - 2):
x = nums[i]
if i > 0 and x == nums[i - 1]:
continue
j = i + 1
k = n - 1
while j < k:
s = x + nums[j] + nums[k]
if s > 0:
k -= 1
elif s < 0:
j += 1
else:
a.append([x, nums[j], nums[k]])
j += 1 # 因为还要继续寻找,不止一组
while j < k and nums[j] == nums[j - 1]:
j += 1
k -= 1
while k > j and nums[k] == nums[k + 1]:
k -= 1
return a
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
ranges::sort(nums);
vector<vector<int>> a;
int n=nums.size();
for(int i=0;i<n-2;i++){
int x=nums[i];
if(i>0 && x==nums[i-1]) continue;
int low=i+1,high=n-1;
while(low<high){
int s=x+nums[low]+nums[high];
if (s>0){
high--;
}
else if (s<0){
low++;
}
else{
a.push_back({x,nums[low],nums[high]});
for(low++;low<high && nums[low]==nums[low-1];low++);
for(high--;low<high && nums[high]==nums[high+1];high--);
}
}
}
return a;
}
};
for(low++;low<high && nums[low]==nums[low-1];low++);常用于跳过重复元素
第一个low++是赋初值
#include <iostream>
#include <vector>
#include <ranges>
#include <algorithm>
int main() {
std::vector<int> nums = {4, 2, 9, 5, 1};
std::ranges::sort(nums);
for (int num : nums) {
std::cout << num << " ";
}
return 0;
}