KSum问题

KSum是Leetcode上的一系列问题,本质上还是hash问题。现在从最基本的2Sum开始拓展到KSum.

Two Sum

  Total Accepted: 112324   Total Submissions: 635568


Given an array of integers, 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.


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





这个问题最容易想到的是排好序后用两个指针一前以后遍历,但是这种情况会比较复杂,因为排好序后的数字与排序前的数字的对应关系打乱了,而且需要额外的存储空间。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int l = 0;
        int r = nums.size()-1;
        vector<int> res;
        vector<int> tmp = nums;
        sort(nums.begin(),nums.end());
        while(l<r) {
            int sum = nums[l] + nums[r];
            if(sum == target) break;
            if(sum < target) l++;
            if(sum > target) r--;
        }
        
        int i,j;
       
        for(i = 0; i <tmp.size();++i){
            if(tmp[i] == nums[l]) {
                break;
            }
        }
        
                
        for(j =0; j <tmp.size();j++){
            if(tmp[j] == nums[r] && j!=i){
                break;
            }
        }
        if(i<j) {
            res.push_back(i+1);
            res.push_back(j+1);
        }
        
        else{
            res.push_back(j+1);
            res.push_back(i+1);
        }

        return res;
    }
    

};

这个方法改进一下就是用hash存储对应关系

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int ,int> map;
        vector<int> res;
        
        for(int i = 0; i < nums.size();i++){
            map[nums[i]] = i;
        }
        
        for(int i = 0 ; i < nums.size();i++){
            int gap = target - nums[i];
            if(map.find(gap)!=map.end()&& map[gap] >i){
                res.push_back(i+1);
                res.push_back(map[gap] + 1);
                break;
            }
        }
        return res;
    }
    

};

class Solution {
public:
    vector<int> twoSum(vector<int> &nums, int target) {
        unordered_map<int,int> map;
        vector<int> res;
        
        for(int i = 0; i < nums.size(); i++) {
            int gap = target - nums[i];
            
            if(map.find(gap) != map.end()){
                res.push_back(map[gap] +1);
                res.push_back(i +1);
            }
            
            map[nums[i]] = i; 
        }
        return res;
    }
};

这两个代码有些许差别,但是本质是一样的,因为hash对于同一种情况会查找2次。

3Sum

  Total Accepted: 64124   Total Submissions: 379395

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)


class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> result;
        if(nums.size() < 3) return result;
        sort(nums.begin(),nums.end());
        for(int i = 0; i < nums.size(); i++) {
            int target = 0 - nums[i];
            int l = i+1;
            int r = nums.size()-1;
            vector<int> res;
            while(l<r){
                int sum = nums[l] + nums[r];

                if(sum < target)  l++;
                else if(sum > target ) r--;
                else{
        
                    vector<int> triplet(3, 0);
                    triplet[0] = nums[i];
                    triplet[1] = nums[l];
                    triplet[2] = nums[r];
                    result.push_back(triplet);
                    while(l<r && nums[l] == triplet[1]) l++;
                    while(l<r && nums[r] == triplet[2]) r--;
                }
            }
            while( i+1 < nums.size() &&nums[i+1] == nums[i]) i++;
        }
        return result;
    }
    
};

3Sum Closest

  Total Accepted: 44277   Total Submissions: 164621

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
         int ans = 0;
        if(nums.size() <=3){
            for(int i = 0 ; i <nums.size(); i++){
                ans +=nums[i];
            }
            return abs(ans);
        }
        
        
        for(int i = 0 ; i < nums.size()-2; i++) {
            int l = i+1;
            int r = nums.size()-1;
            while(l<r) {
                int sum =nums[i]+nums[l]+nums[r];
                if(abs(target-sum)< abs(target-ans)) {
                    ans = sum;
                    if(ans == 0) return ans;
                }
                (sum > target) ? r--:l++;
            }
        }
        return ans;
        
    }
};

思想和3Sum是类似的

4Sum

  Total Accepted: 40527   Total Submissions: 187175


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

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • The solution set must not contain duplicate quadruplets.

    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

    A solution set is:
    (-1,  0, 0, 1)
    (-2, -1, 1, 2)
    (-2,  0, 0, 2)

<span style="font-family: Arial, Helvetica, sans-serif;">class Solution {</span>
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> result;
        if(nums.size() < 4) return result;
        sort(nums.begin(),nums.end());
        
        unordered_map<int, vector<pair<int,int>>> cache;
        
        for(int a = 0; a <nums.size(); ++a) {
            for(int b = a+1; b <nums.size(); ++b) {
                cache[nums[a]+nums[b]].push_back(pair<int,int>(a,b));
            }
        }
        
        for(int c = 0 ; c < nums.size(); ++c) {
            for(int d = c+1; d<nums.size(); d++) {
                int key = target - nums[c] - nums[d];
                if(cache.find(key) == cache.end()) continue;
                
                vector<pair<int,int>> vec = cache[key];
                for(int k= 0; k < vec.size(); ++k) {
                    if(c <= vec[k].second)
                        continue;
                    result.push_back({nums[vec[k].first], nums[vec[k].second], nums[c],nums[d]});
                }
            }
        }
        
        sort(result.begin(),result.end());
        result.erase(unique(result.begin(), result.end()), result.end());
    }
};

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& num, int target) {
        vector<vector<int>> res;
        if (num.size() < 4) return res;
        sort(num.begin(),num.end());
        
        for(int i = 0; i< num.size();i++){
            int target3 = target - num[i];
            for(int j = i+1 ; j <num.size(); j++){
                int target2 = target3 - num[j];
                int l = j+1, r = num.size() -1;
                while(l<r) {
                    int sum = num[l] + num[r];
                    if(sum < target2) l++;
                    else if(sum > target2) r--;
                    else{
                        vector<int> ans(4,0);
                        ans[0] = num[i];
                        ans[1] = num[j];
                        ans[2] = num[l];
                        ans[3] = num[r];
                        res.push_back(ans);
                        
                        while(l<r && num[l] == ans[2]) ++l;
                        while(l<r && num[r] == ans[3]) --r;
                    }
                }
                while(j+1 < num.size() && num[j+1] == num[j]) ++j;
            }
            while(i+1 < num.size() && num[i+1] == num[i]) ++i;
        }
        return res;
    }
};












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值