【LeetCode】leetcode sum问题汇总小结

1. 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].


两个数相加,所以通过hash表记录数a与数target-a有没有出现过即可,因为还要记录下标,所以用hash。
并且由于从前到后遍历,且只有一个答案,所以遍历一次即可。
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
         vector<int> rst;
         unordered_map<int,int> hash;
         for(int i=0;i<nums.size();i++)
         {
         	int n=target-nums[i];
             if(hash.find(n)!=hash.end())
             {
                 rst.push_back(hash[target-nums[i]]);
                 rst.push_back(i);
                 return rst;
             }else hash[nums[i]]=i;
         }
 
        return rst;
    }
};
2. 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]
]
这题结果可能有重复,并且不要求输出下标,所以可以先排序,再每次固定第一个数,对后两个数用two pointer。front back
如果front+back+first>0,back--,反之front++.为了避免重复,跳过重复的数。
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> rst;
        sort(nums.begin(),nums.end());
        for(int i=0;i<nums.size();i++)
        {
        	if(i>0&&nums[i]==nums[i-1]) continue;   //跳过跟n1重复的
            int n1=nums[i];
            int front=i+1;
            int back=nums.size()-1;
            while(front<back)
            {
                n2=nums[front];
                n3=nums[back];
                if(n1+n2+n3<0) front++;
                else if(n1+n2+n3>0) back--;
                else{
                	vector<int> tmp{n1,n2,n3};
                	rst.push_back(tmp);
                	while(front<back&&nums[front]==n2) front++;  //跳过跟n2重复的
                	while(front<back&&nums[back]==n3) back--;    //跳过跟n3重复的
                }

            }
        }
        
       
        return rst;
    }
};


3. 3Sum Closest

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 fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        int rst=0,len=A.size();
        unordered_map<int,int> hasha,hashb,hashc,hashd;
        sort(A.begin(),A.end());
        sort(B.begin(),B.end());
        sort(C.begin(),C.end());
        sort(D.begin(),D.end());
        inithash(A,hasha);
        inithash(B,hashb);
        inithash(C,hashc);
        inithash(D,hashd);
        if(A[0]+B[0]+C[0]+D[0]>0) return 0;
        if(A[len-1]+B[len-1]+C[len-1]+D[len-1]<0) return 0;
        for(int i=0;i<len;i++)
        {
            if(i>0&&A[i]==A[i-1]) continue;
            int sum3=0-A[i];
            for(int j=0;j<len;j++){
                if(j>0&&A[j]==A[j-1]) continue;
                if(B[j]+C[j]+D[j]>0) break;
                if(B[len-1]+B[len-1]+C[len-1]<0)
                
            }

        }
        
        
        
    }
    void inithash(vector<int>&A, unordered_map<int,int> &hash){
        for(int i=0;i<A.size();i++){
            if(hash.find(a)==hash.end()) hash[a]=1;
            else hash[a]++;
        }
    }
};

18. 4Sum

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

跟3sum比较像,不过升级到四个 可以固定前两个,再加个循环,O(n^3)的复杂度。参考大神的代码发现还可以剪枝
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> total;
        int n = nums.size();
        if(n<4)  return total;
        sort(nums.begin(),nums.end());
        for(int i=0;i<n-3;i++)
        {
            if(i>0&&nums[i]==nums[i-1]) continue;
            if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target) break;
            if(nums[i]+nums[n-3]+nums[n-2]+nums[n-1]<target) continue;
            for(int j=i+1;j<n-2;j++)
            {
                if(j>i+1&&nums[j]==nums[j-1]) continue;
                if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target) break;
                if(nums[i]+nums[j]+nums[n-2]+nums[n-1]<target) continue;
                int left=j+1,right=n-1;
                while(left<right){
                    int sum=nums[left]+nums[right]+nums[i]+nums[j];
                    if(sum<target) left++;
                    else if(sum>target) right--;
                    else{
                        total.push_back(vector<int>{nums[i],nums[j],nums[left],nums[right]});
                        do{left++;}while(nums[left]==nums[left-1]&&left<right);
                        do{right--;}while(nums[right]==nums[right+1]&&left<right);
                    }
                }
            }
        }
        return total;
    }
};



19. 4Sum II

Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

因为这题只需要求个数,而不需要具体的下标值,所以可以两个一组求和,对各和的值做hash记录,遍历一个hash,在另一个hash中查找是否出现过使和为target的值,两个值的个数求和。

class Solution {
public:
    void fillMap(vector<int>& A, vector<int>& B, unordered_map<int,int> &m)
    {
        int n = A.size();
        for(int i = 0; i < n; ++i)
        for(int j = 0; j < n; ++j)
          ++m[A[i] + B[j]];
          
    }
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        unordered_map<int,int> m1, m2;
        fillMap(A, B, m1);
        fillMap(C, D, m2);
        int res = 0;
        for(auto it = m1.begin(); it != m1.end(); ++it)
        {
           auto it2 = m2.find(-it->first);
           if(it2 != m2.end())
             res += it->second*it2->second;
        }
        return res;
    }



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值