15三数之和

题目链接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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值