哈希表之:two sum / three sum / four sum

这篇博客介绍了如何使用哈希表解决数组中两数、三数、四数之和等于给定值的下标问题。通过排序、哈希映射和双指针等技巧,分别解决了two sum、three sum和four sum的高效算法,其中重点强调了利用set去重的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,two sum:返回数组里面两个数加起来等于给定值的数字的下标

思路:用哈希表来做,在这了直接用了STL中的map将数值与下标进行了映射

代码:

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
	    vector<int> res;
	    map<int, int> m;
	    for(int i = 0; i < numbers.size(); ++i){
	        if(m.find(target - numbers[i]) != m.end()){
	            res.push_back(m[target - numbers[i]] + 1);
	            res.push_back(i + 1);
	            break;    //注意这个break的添加
	        }
	        m[numbers[i]] = i;
    	}
	    return res;
    }
};
	    

 

2,three sum :返回数组里面3个数加起来为0的所有组合(不能重复)

 

思路:(1)首先对数组进行排序(从小到大)

 (2)依次取出第i个数,(i从0开始),并且不重复的选取(跳过重复的数)

(3)这样就转为求两个数相加等于给定数的问题(用双指针)

对于求2个数相加等于给定数的思路:

(1)定义两个指针:左指针(left)和右指针(right)

(2)找出固定left,此时left所指的值为数组中最小的值。然后找出两个数的和不大于target的最大right的位置

(3)调整left的位置(往后移),求解和是否为target(O(n));

对于以上的总体的时间复杂度为:O(nlogn) + O(n);

代码:

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        vector<vector<int> > res;
	    if(num.size() < 3)
	        return res;
	    sort(num.begin(), num.end());
	    int n = num.size();
        for(int i = 0; i < n; ++i){
	        //去掉重复,这一步是很关键的,一定要加
	        if(i == 0 || num[i] != num[i-1]){
	            int l = i+1, r = n-1;
	            while(l < r){
	                if(num[i] + num[l] + num[r] == 0){
	                    vector<int> tmp(3);
	                    tmp[0] = num[i];
	                    tmp[1] = num[l];
                        tmp[2] = num[r];
	                    res.push_back(tmp);
	                    while(l < r && num[l] == tmp[1])   
                            ++l;  //这一步是去掉重复的,也很关键
	                }else if(num[i] + num[l] + num[r] > 0){
	                    r--;
	                }else
	                    l++;
	            }
            }
	    }
	    return res;
    }
};

从上面我们可以看到,我们要对重复的数字进行去掉,这其实比较麻烦的。稍有不慎,就没有处理好。所以我们可以把结果保存在在一个set里面,这样就能够自动去重的。 

下面的是另外一种思路:

由于不能有重复的,故可以用set来保存结果,这样的可定是不会重复的

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        //另外一种思路,为了防止里面有重复的,可以用set
        vector<vector<int> > res;
        set<vector<int> > st;
        sort(num.begin(), num.end());
        int n = num.size();
        for(int i = 0; i < n; ++i){
            int l = i+1, r = n-1;
            while(l < r){
                int sum = num[i] + num[l] + num[r];
                if(sum == 0){
                    vector<int> tmp(3,0);
                    tmp[0] = num[i];
                    tmp[1] = num[l];
                    tmp[2] = num[r];
                    st.insert(tmp);
                }
                if(sum > 0){
                    --r;
                }else
                    ++l;
            }
        }
        for(auto it = st.begin(); it != st.end(); ++it)
            res.push_back(*it);
        return res;
    }
};

 

3,four sum :返回数组里面所有4个数字加起来等于给定值的组合

题目描述

 

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)

 

从上面的3 Sum可以总结出一中方法:用set来保存结果,这样有自动去重功能

代码:

class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        vector<vector<int> > res;
        set<vector<int> > st;
        int n = num.size();
        sort(num.begin(), num.end());
        for(int i = 0; i < n; ++i){
            for(int j = i+1; j < n; ++j){
                int l = j+1, r = n-1;
                while(l < r){
                    int sum = num[i] + num[j] + num[l] + num[r];
                    if(sum == target){
                        vector<int> temp(4,0);
                        temp[0] = num[i];
                        temp[1] = num[j];
                        temp[2] = num[l];
                        temp[3] = num[r];
                        st.insert(temp);
                    }
                    if(sum < target){
                        ++l;
                    }else{
                        --r;
                    }
                }
            }
        }
        for(auto it = st.begin(); it != st.end(); ++it)
            res.push_back(*it);
        return res;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值