zoukankan      html  css  js  c++  java
  • 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:

    • 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)
    

    Subscribe to see which companies asked this question

    class Solution {
    public:
        /*
         * 固定两个点,然后使用two sum 求解
         * 注意去掉重复的点
         */
        void two_sum(vector<int>& nums, vector<vector<int>>& res, int start_index, int last_index, int target) {
            int i = start_index + 1;
            int j = last_index - 1;
            while (i < j) {
                if (nums[i] + nums[j] == target) {
                    vector<int> tmp;
                    tmp.push_back(nums[start_index]);
                    tmp.push_back(nums[i]);
                    tmp.push_back(nums[j]);
                    tmp.push_back(nums[last_index]);
                    res.push_back(tmp);
                    cout << nums[start_index] << nums[i] << nums[j] << nums[last_index] << endl;
                    i++;
                    while (nums[i] == nums[i-1]) {
                        i++;
                    }
                    j--;
                    while (nums[j] == nums[j+1]) {
                        j--;
                    }
                } else if (nums[i] + nums[j] > target) {
                    j--;
                } else {
                    i++;
                }
            }
        }
    
        vector<vector<int>> fourSum(vector<int>& nums, int target) {
            int size = nums.size();
            vector<vector<int>> res;
            sort(nums.begin(), nums.end());
            int i;
            int j;
            for (i=0; i<size-2; i++) {
                //过滤掉相同的左边点,防止出现重复的结果
                if (i > 0 && nums[i] == nums[i-1]) {
                    continue;
                }
                for (j=size-1; j>i+1; j--) {
                    if (j < size-1 && nums[j] == nums[j+1]) {
                        continue;
                    }
                    two_sum(nums, res, i, j, target- nums[i] - nums[j]);
                }
            }
            return res;
        }
    };
  • 相关阅读:
    Druid初步学习
    跨区域的application共享问题。
    jsp系统时间和时间对比(活动结束不结束)
    Intellij Idea中运行tomcat 报內存溢出
    SpringMVC -rest风格修改删除
    Redis服务器的创建服务
    Double和double的区别
    1.Redis安装(转)
    查看Mysql执行计划
    linux查询日志命令总结
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5107674.html
Copyright © 2011-2022 走看看