[LeetCode]4Sum

栏目: 编程工具 · 发布时间: 7年前

内容简介:本题的思路和3Sum一致,无非是多加一层循环。当然,时间复杂度就为O(n^3)了。时间复杂度:O(n^3)空间复杂度:O(n)

原题

Given an array nums of  n integers and an integer  target , are there elements  abc , and  d in  nums such that  abcdtarget ? Find all unique quadruplets in the array which gives the sum of  target .

Note:

The solution set must not contain duplicate quadruplets.

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]
]

题解

本题的思路和3Sum一致,无非是多加一层循环。当然,时间复杂度就为O(n^3)了。

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector< vector<int> > rs;
        sort(nums.begin(), nums.end());
        int l = nums.size(), f = 0, b = 0;
        for (int i = 0; i < l - 3; ++i) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < l - 2; j++) {
                f = j + 1;
                b = l - 1;
                if (j - i > 1 && nums[j] == nums[j - 1]) continue;
                while (f < b) {
                    if (nums[i] + nums[j] + nums[f] + nums[b] < target) {
                        while (nums[f] == nums[++f]) {}
                    } else if(nums[i] + nums[j] + nums[f] + nums[b] > target) {
                        while (nums[b] == nums[--b]) {}
                    } else {
                        vector<int> tmp = {nums[i], nums[j], nums[f], nums[b]};
                        rs.push_back(tmp);
                        while (nums[f] == nums[++f]) {}
                        while (nums[b] == nums[--b]) {}
                    }
                }
            }
        }
        return rs;
    }
};

时间复杂度:O(n^3)

空间复杂度:O(n)


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

解码宇宙

解码宇宙

(美) 塞费 / 隋竹梅 / 上海科技教育出版社 / 2010-4 / 26.00元

《解码宇宙:新信息科学看天地万物》:宇宙,或许就是一台庞大的计算机。这是查尔斯·塞费在《解码宇宙:新信息科学看天地万物》中对宇宙做出的结论。作者从信息的特点开始谈起,详细论述了信息论和量子计算,向我们展示了一种不可思议的拜占庭式宇宙的情景,涉及生命的本质、热力学、相对论、量子力学、黑洞、多重宇宙,直至宇宙的命运。《解码宇宙:新信息科学看天地万物》资料翔实,内容丰富多彩,思路清晰,观点明确,读后使人......一起来看看 《解码宇宙》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

随机密码生成器
随机密码生成器

多种字符组合密码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试