• LeetCode——3Sum


    1. Question

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

    Note: 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]
    ]

    2. Solution

    1. 先排序,然后对于每一个nums[i],在其后找到两个数字num[j]和num[k],j<k,使得三者和为0。

    2. 去掉重复的组合,如果满足三者为0,那么j需要后移到一个不同的数,k也需要前移到一个不同的数。

    3. 重复的nums[i]也需要去掉,因为nums[i]和nums[i+1] 都是和其后的进行组合,如果两个一样的话,就重复了,需要去掉。

    3. Code

    class Solution {
    public:
        vector<vector<int>> threeSum(vector<int>& nums) {
            if (nums.size() <= 2)
                return vector<vector<int>>();
            sort(nums.begin(), nums.end());
            vector<vector<int>> res;
            for (int i = 0; i < nums.size() - 2; i++) {
                int start = i + 1;
                int end = nums.size() - 1;
                while (start < end) {
                    int tmp = nums[start] + nums[end];
                    int target = -nums[i];
                    if (tmp == target) {
                        vector<int> ele;
                        ele.push_back(nums[i]);
                        ele.push_back(nums[start]);
                        ele.push_back(nums[end]);
                        res.push_back(ele);
                        
                        // 去掉start重复的
                        while (start < end && nums[start] == ele[1])
                            start++;
                        // 去掉end重复的
                        while (end > start && nums[end] == ele[2])
                            end--;
                    } else if (tmp > target)
                        end--;
                    else
                        start++;
                }
                // 去掉nums[i]重复的
                while (i + 1 < nums.size() - 2 && nums[i + 1] == nums[i])
                    i++;
            }
            return res;
        }
    };
    
  • 相关阅读:
    WPF 下两种图片合成或加水印的方式(转载)
    Git reset与checkout的区别
    C# 串口导致电脑蓝屏一个可能的原因
    两个用于win7任务栏显示进度的dll
    批量远程执行shell命令工具
    基于zookeeper的主备切换方法
    代码的演变随记
    svn错误:Can't convert string from 'UTF-8' to native encoding
    not allowed to access to crontab because of pam configuration
    大数据利器
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7797745.html
Copyright © 2020-2023  润新知