LeetCode - 15 - 3Sum(内有two sum)

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

唔,虽说N sum都是套路了,然额很早就写了two sum,当时数组是乱序所以拿map写的,到了3 sum就还是有点懵,感觉那个办法没法用了。其实还是可以用,只不过初始化的位置不同罢了。

然额,然额,为喵评论区的写法永远更优雅QAQ

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int> > ans;
        if (nums.empty()) return ans;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); ++i) {
            if (i == 0 || nums[i] != nums[i-1]) {
                int le = i + 1, ri = nums.size() - 1;
                int sum = 0 - nums[i];
                while (le < ri) {
                    if (nums[le] + nums[ri] == sum) {
                        vector<int> loc;
                        loc.push_back(nums[i]);
                        loc.push_back(nums[le]);
                        loc.push_back(nums[ri]);
                        ans.push_back(loc);
                        le++;
                        while (le < ri && nums[le] == nums[le-1]) le++;
                        ri--;
                        while (le < ri && nums[ri] == nums[ri+1]) ri--;
                    }
                    else if (nums[le] + nums[ri] < sum) le++;
                    else ri--;
                }
            }
        }
        return ans;
    }
};




167. Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

排好序的two sum【托腮】那就是套路咯,总结写这好了,也懒得开新的了(其实是因为CSDN每天最多发5篇博客QAQ,草稿箱还有一堆未发表的嘤嘤嘤)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ans;
        int le = 0, ri = nums.size() - 1;
        while (le < ri) {
            if (nums[le] + nums[ri] == target) {
                ans.push_back(le+1);
                ans.push_back(ri+1);
                break;
            }
            else if (nums[le] + nums[ri] < target) le++;
            else ri--;
        }
        return ans;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值