Leetcode 18 - 4Sum

题目

https://leetcode.com/problems/4sum/

题意

给出一个整数序列和一个数值target,对于这个序列中任意四个数有可能等于target。

请返回和等于target的四个数的所有情况。

Example:

Given array nums = [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]
]

思路

author's blog == http://www.cnblogs.com/toulanboy/

这道题是3Sum的拓展。

思路很简单,我们只需将第1个数固定,然后去讨论3sum的情况即可。

如果不懂3Sum的解法,可以参考https://www.cnblogs.com/toulanboy/p/10900105.html。

代码

//author's blog == http://www.cnblogs.com/toulanboy/
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        int i, j, k, p;
        sort(nums.begin(), nums.end());
        vector<vector<int>> result;
        //固定i
        for(i=0; i<(int)nums.size(); ++i){
            if(i != 0 && nums[i] == nums[i-1])
                continue;
            if(target > 0 && nums[i] > target)
                return result;
            //剩余的逻辑和求3个和一样,逻辑讲解:https://www.cnblogs.com/toulanboy/p/10900105.html
            for(j = i+1; j<(int)nums.size()-2; ++j){
                if(j != i+1 && nums[j] == nums[j-1])
                    continue;
                
                k = j+1;
                p = nums.size() - 1;
                while(k < p){
                    int sum = nums[i] + nums[j] + nums[k] + nums[p];
                    if(sum == target){
                        vector<int> tmp;
                        tmp.push_back(nums[i]);
                        tmp.push_back(nums[j]);
                        tmp.push_back(nums[k]);
                        tmp.push_back(nums[p]);
                        result.push_back(tmp);
                    }
                    if(sum <= target){
                        while(k < p && nums[k+1] == nums[k]){
                            k++;
                        }
                        k++;
                    }
                    else if(sum > target){
                        while(k < p && nums[p-1] == nums[p]){
                            p--;
                        }
                        p--;
                    }
                }
        
            }
            
        }
        return result;
    }
};//author's blog == http://www.cnblogs.com/toulanboy/

运行结果

Runtime: 48 ms
Memory Usage: 9.4 MB
posted @ 2019-05-23 18:02  偷懒人  阅读(138)  评论(0编辑  收藏  举报