lintcode 四数之和

作者: yzawyx0220 | 来源:发表于2017-01-04 09:59 被阅读113次

给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。
注意事项
四元组(a, b, c, d)中,需要满足a <= b <= c <= d
答案中不可以包含重复的四元组。
样例
例如,对于给定的整数数组S=[1, 0, -1, 0, -2, 2] 和 target=0. 满足要求的四元组集合为:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
题目链接:http://www.lintcode.com/zh-cn/problem/4sum/

与上一道题三数之和类似,只不过四数之和多了一个指针,按照这个思路,n数之和都可以这么做。

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
        sort(nums.begin(),nums.end());
        vector<vector<int> > res;
        for (int i = 0;i < nums.size() - 3;i++) {
            if (i > 0 && nums[i - 1] == nums[i]) continue;
            if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break;
            for (int j = i + 1;j < nums.size() - 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;
                int left = j + 1,right = nums.size() - 1;
                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum > target) right--;
                    else if (sum < target) left++;
                    else {
                        res.push_back({nums[i],nums[j],nums[left],nums[right]});
                        do{left++;} while (left < right && nums[left] == nums[left - 1]);
                        do{right--;} while (left < right && nums[right] == nums[right + 1]);
                    }
                }
            }
        }
        return res;
    }
};

相关文章

  • lintcode 四数之和

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

  • LintCode 58-四数之和

  • 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 四数之和

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