美文网首页
LintCode 58-四数之和

LintCode 58-四数之和

作者: 胡哈哈哈 | 来源:发表于2016-05-21 17:01 被阅读119次
class Solution {
public:
    /**
     * @param numbers: Give an array numbersbers of n integer
     * @param target: you need to find four elements that's sum of target
     * @return: Find all unique quadruplets in the array which gives the sum of 
     *          zero.
     */
    vector<vector<int> > fourSum(vector<int> nums, int target) {
        // write your code here
        vector<vector<int>> ret;
        set<int> dup;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); ++i) {
            for (int j = i + 1; j < nums.size(); ++j) {
                unordered_set<int> s;
                for (int k = j + 1; k < nums.size(); ++k) {
                    int r = target - nums[i] - nums[j] - nums[k];
                    if (r < nums[j]) break;
                    if (r <= nums[k] && s.find(nums[k]) != s.end()) {
                        int h = hash(nums[i], nums[j], r, nums[k]);
                        if (dup.find(h) == dup.end()) {
                            vector<int> ans({nums[i], nums[j], r, nums[k]});
                            ret.push_back(ans);
                            dup.insert(h);
                        }
                    } else {
                        s.insert(r);
                    }
                }
            }
        }
        return ret;
    }
    
    int hash(int a, int b, int c, int d) {
        return a + 10 * b + 100 * c + 35937 * d;
    }
};

相关文章

  • LintCode 58-四数之和

  • lintcode 四数之和

    给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。注意事项...

  • lintcode 三数之和

    给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。注意...

  • lintcode 两数之和

    给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。你需要实现的函数twoSum需要返回这两个数...

  • LintCode三数之和系列问题

    三数之和 LintCode57 三数之和解题思路:先对数组排序,然后开始遍历,对于数组中的每一个元素,用两指针往中...

  • LintCode - 两数之和(普通)

    版权声明:本文为博主原创文章,未经博主允许不得转载。 难度:容易 要求: 给一个整数数组,找到两个数使得他们的和等...

  • algrithrom

    求和问题,双指针解决 done 两数之和 三数之和 最接近三数之和 四数之和 链表反转问题 done 链表反转 链...

  • 两数之和&三数之和&四数之和&K数之和

    今天看了一道谷歌K数之和的算法题,忽然想起来之前在力扣上做过2、3、4数之和的题,觉得很有必要来整理一下。其实2、...

  • LintCode 57. 三数之和

    原题 解 第一步,万年不变的查错。如果给的array是null或不够三个数,直接return 空的result。因...

  • LintCode 57-三数之和

    分析 注意hash去重

网友评论

      本文标题:LintCode 58-四数之和

      本文链接:https://www.haomeiwen.com/subject/glhorttx.html