• 15.3sum


    Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

    Note:

    • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
    • The solution set must not contain duplicate triplets.
        For example, given array S = {-1 0 1 2 -1 -4},
        A solution set is:
        (-1, 0, 1)
        (-1, -1, 2)

        此题的思路是首先将数组排序,再依次固定一个元素作为a(a的下标取值范围是[0,n-2),其中n为数组的大小),需要注意的是,这个固定的元素需要跳过重复出现的数字。然后取固定的元素后面的一个元素,设其下标为left,取数组的最后一个元素,设其下标为right。现在开始求以上3个元素的和,直至left≥right退出循环。如果和sum为0,那么将这3个数加入最终需要返回的数组。并更新left和right的下标,left++,right--。请注意,也需要跳过重复出现的数字。如果和sum大于0,那么将right减去1,否则,如果sum的和小于0,那么将left加上1。这是因为数组已经排好序,如果和sum>0,只能选取较小的数来求和,left对应的数不能再小了,只能降低right对应数的值,所以将right的值减去1。而如果sum<0,只能取较大的数来求和,right对应的数不能再大了,只能增加left对应数的值,所以将left的值加上1。这样就能求出所有满足要求的组合,而且不会有重复。

    class Solution {
    private:
        vector<vector<int>> result;
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            if(nums.size()<3)
                return result;
            sort(nums.begin(),nums.end());
            vector<int>temp(3);
            for(int i=0;i<nums.size()-2;i++){
                if(i!=0&&nums[i]==nums[i-1])
                    continue;
                int left=i+1;
                int right=nums.size()-1;
                while(left<right){
                    int sum=nums[i]+nums[left]+nums[right];
                    if(sum==0){
                        temp[0]=nums[i];
                        temp[1]=nums[left];
                        temp[2]=nums[right];
                        left++;
                        right--;
                        result.push_back(temp);
                        while(left<right&&nums[left]==nums[left-1])
                            left++;
                        while(left<right&&nums[right]==nums[right+1])
                            right--;
                    }
                    else if(sum>0)
                        right--;
                    else
                        left++;
                }
            }
            return result;
        }
    };
  • 相关阅读:
    【NodeJS】---express配置ejs mongoose route等
    【CSS3】---层模型position之fixed固定定位、absolute绝对定位和relative相对定位
    【CSS3】---:before :after生成内容
    px转rem的填坑之路
    markdown编写文件目录结构
    js reduce数组转对象
    处理Promise.reject()
    js事件循环
    为什么[] == false 为true
    为什么不建议用var
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5114405.html
Copyright © 2020-2023  润新知