[LeetCode]4Sum
2015-11-10 15:27
316 查看
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.
4sum,可以归纳为3sum问题,这样复杂度 O(N^3)。但是实际中可以通过一些细节处理提高遍历无用解的情形。
16ms
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)
4sum,可以归纳为3sum问题,这样复杂度 O(N^3)。但是实际中可以通过一些细节处理提高遍历无用解的情形。
16ms
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int>> ret; int len = nums.size(); sort(nums.begin(),nums.end()); for(int i=0;i<len-3;++i){ if(i>0&&nums[i]==nums[i-1]) continue;//dup start if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target) break;//no result if(nums[i]+nums[len-1]+nums[len-2]+nums[len-3]<target) continue;//at this start no result,go to next one,important for(int j=i+1;j<len-2;++j){//3 sum if(j>i+1&&nums[j]==nums[j-1]) continue;//dup start if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target) break;//优化的关键 if(nums[i]+nums[j]+nums[len-1]+nums[len-2]<target) continue; //优化的关键 int left = j+1; int right = len-1; while(left<right){ if(nums[i]+nums[j]+nums[left]+nums[right]==target){ ret.push_back({nums[i],nums[j],nums[left],nums[right]}); ++left; --right; while(nums[left]==nums[left-1]&&nums[right]==nums[right+1]){ //重复子解,重要 ++left; --right; } } else if(nums[i]+nums[j]+nums[left]+nums[right]<target){ ++left; while(nums[left]==nums[left-1]){//重复解,重要 ++left; } } else if(nums[i]+nums[j]+nums[left]+nums[right]>target){ --right; while(nums[right]==nums[right+1]){ //重复解 --right; } } } } } return ret; } };
相关文章推荐
- 主activity报空指针异常java.lang.RuntimeException: Unable to resume activity
- 开源之后的小幸福
- Xcode 6制作动态及静态Framework
- Android Appium Server从启动到case完成的活动分析
- Oracle修改数据表
- 超大次幂思路
- c+(内存)
- Android开发UI之隐藏系统状态栏
- * daemon not running. starting it now * ADB server didn't ACK * failed to start daemon *
- Too many arguments to function call, expected 0, have 3
- javascript 定时器工作原理
- ViewPager轮播效果
- cameraservice如何跨进程传递video数据(准备工作)
- Build QT project in ROS
- 关于 PreparedStatement 返回值的问题
- c++(递归和堆栈)
- 办公室站队的一地鸡毛
- ios-单例模式
- grunt打包UEditor示例
- 二分查找(两行代码)