leetcode001-2Sum,3Sum

来源:互联网 发布:colbie caillat 知乎 编辑:程序博客网 时间:2024/05/08 08:24

2Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

这道题直接二重循环暴力解很有可能会超时,我就试了一下,竟然没有。

vector<int> twoSum(vector<int>& nums, int target) {        std::vector<int> ans;        for (int i = 0; i < nums.size()-1; i++) {            for (int j = i+1; j < nums.size(); j++) {                if (nums[i] + nums[j] == target) {                    ans.push_back(i);                    ans.push_back(j);                    return ans;                }            }        }        return ans;    }


但从judge的结果来看,很显然有更好的方法。看了讨论区的内容,发现基本思路是利用哈希表的快速查找来实现O(n)的时间复杂度,根据思路自己尝试了实现。

vector<int> twoSum(vector<int>& nums,int target) {        std::vector<int> ans;        std::map<int,int> hashmap;        for (int i =0; i < nums.size(); i++) {            if (!hashmap.count(nums[i])) {                hashmap.insert(make_pair(nums[i],i));            }            if (hashmap.count(target-nums[i])) {                int another = hashmap[target-nums[i]];                if (another != i) {                    ans.push_back(another);                    ans.push_back(i);                }            }        }        return ans;    }


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: 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]]
这道题三重循环O(n^3)显然是不可能会AC的,我考虑了一下,觉得应该可以通过结合O(n) 的2Sum将时间复杂度降到O(n^2)

最外层循环是给定数组,每次固定一个元素,在剩余的元素中寻找相加结果为给定元素相反数的组合。

想了一下,2Sum的题目是对于每个数都有唯一的组合,而在这里要套用的话,必须是允许没有组合或者有多个不重复的组合。

于是我修改了一下,但是仍然超时,以下是超时的代码

class Solution {public:   vector<vector<int>> threeSum(vector<int>& nums) {        vector<vector<int>> ans;        if (nums.size() < 3) return ans;        sort(nums.begin(),nums.end());        int a;        for (int i = 0; i < nums.size(); i++) {            if (i > 0 && nums[i] == nums[i-1]) {                continue;            } else {                a = nums[i];            }                        // b+c=-a            bool flag = false;            map<int, int> hashmap;            for (int j = i+1; j < nums.size(); j++) {                if (!hashmap.count(nums[j])) {                    flag = false;                    hashmap.insert(make_pair(nums[j], j));                } else if(flag) {                     continue;                }                if (hashmap.count(-a-nums[j])) {                    int another = hashmap[-a-nums[j]];                    if (another != j) {                        flag = true;                        vector<int> ans1;                        ans1.push_back(a);                        ans1.push_back(-a-nums[j]);                        ans1.push_back(nums[j]);                        ans.push_back(ans1);                    }                }            }        }            return ans;    }};

实在解决不了,我上网搜了一下,发现里面那层针对排序后的数组,可以用左右指针来寻找不重复的组合,以下是代码。


 vector<vector<int>> threeSum(vector<int>& nums) {        vector<vector<int>> ans;        if (nums.size() < 3) return ans;        sort(nums.begin(),nums.end());        int a;        for (int i = 0; i < nums.size()-2; i++) {            if (i > 0 && nums[i] == nums[i-1]) {                continue; // 排序后如果前面已经被选作a,相同的数不必再次作为a            } else {                a = nums[i];            }                        // 在数组剩余的后面部分寻找两数之和为-a的组合,结果不能重复            int left = i+1;            int right = nums.size()-1;            while (left < right)            {                if (nums[left] + nums[right] == -a) {                    vector<int> oneAns;                    oneAns.push_back(a);                    oneAns.push_back(nums[left]);                    oneAns.push_back(nums[right]);                    ans.push_back(oneAns);                    while (left < right && nums[left+1] == nums[left]) left++;                    while (right > left && nums[right-1] == nums[right]) right--;                    left++;                    right--;                } else if (nums[left] + nums[right] < -a) {                    left++;                } else {                    right--;                }            }        }        return ans;    }


原创粉丝点击