【LeetCode】LeetCode——第18题:4Sum
2016-05-03 09:57
302 查看
18. 4Sum
My SubmissionsQuestion
Editorial Solution
Total Accepted: 71353 Total
Submissions: 300185 Difficulty: Medium
Given an array S of n integers, are there elements a, b, c, 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)
题目的大概意思是:给定一个数组nums和一个整数target,在nums中找出四个数,使它们的和为target,找出所有这样的不重复的组合。
这道题难度等级:中等
思路:做法跟Two Sum、3
Sum、3 Sum Closest类似,也是使用枚举和夹逼。由于是4个数之和,复杂度会高一些O(n^3)。
1、先将数组排序(升序),再从第一个数开始枚举,遇到相同的跳过,直到最后一个,用k表示枚举第k个数;
2、从第k个枚举后面的数开始,用i表示后面的数;
3、左右夹逼:l、r表示从第i个数开始左右夹逼的下标。
4、在整个枚举和夹逼的过程中l<r始终成立,且要注意跳过一些已经处理过的数,不然会造成结果重复。
代码如下:
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); vector<vector<int> > res; vector<int> tmp(4, 0); int l, r, m; for (int k = 0; k < nums.size(); ++k){ //从第1个数开始枚举 if (k == 0 || nums[k] != nums[k - 1]){ //相同的跳过 for (int i = k + 1; i < nums.size(); ++i){ //从下一个数开始 l = i + 1; r = nums.size() - 1; //左右夹逼 while (l < r){ while (l < r && nums[k] + nums[i] + nums[l] + nums[r] > target){--r;}//限制右边界 if (l < r && nums[k] + nums[i] + nums[l] + nums[r] == target){ tmp[0] = nums[k]; tmp[1] = nums[i]; tmp[2] = nums[l]; tmp[3] = nums[r]; res.push_back(tmp); while(l < r && nums[l] == tmp[2]){++l;} } else{++l;} } m = i; while (nums[i] == tmp[1]){ m = i++; } i = m; } } } return res; } };提交代码 ,AC时间为Runtime: 128ms。
相关文章推荐
- JS基于clipBoard.js插件实现剪切、复制、粘贴
- Eclipse 项目红色叹号:Build Path Problem
- UVA 10003 Cutting Sticks 区间dp
- Java 多线程知识
- 安装 Python3
- 数组的操作
- 打印 目录下 所有的文件夹跟文件
- c语言学习—图书搜索
- PHP包含文件函数include、include_once、require、require_once区别总结
- ubuntu_常用命令_01
- 字符流中第一个不重复的字符
- 【书签】个人常用网站整理及应用推荐
- php使用ffmpeg获取视频信息并截图的实现方法
- 从无到有写一个jQuery开源插件
- all_sort.php
- python re 模块
- perl 包下载官方网站(速度很快的) 和 解压安装指令
- yii2 输出xml格式数据
- 记一次失败的kaggle比赛(3):失败在什么地方,贪心筛选特征、交叉验证、blending
- 京东商品搜索架构设计