leetcode18:4Sum(15-10-6)
2015-10-07 23:41
423 查看
一.题目
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.
二.思路
其实和前面3sum思路差不多,先对数组进行排序,然后分别用两个指针来固定两个元素nums[i],nums[j],再对剩下的两个元素求和,与target-nums[i]-nums[j]进行比较,知道找到相等的为止。
时间复杂度为O(N^3).
三.代码(在3sum基础上延伸过来)
注意几个关键的地方:a,b,c,d这样处理就可以避免重复。
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)
二.思路
其实和前面3sum思路差不多,先对数组进行排序,然后分别用两个指针来固定两个元素nums[i],nums[j],再对剩下的两个元素求和,与target-nums[i]-nums[j]进行比较,知道找到相等的为止。
时间复杂度为O(N^3).
三.代码(在3sum基础上延伸过来)
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { int size=nums.size(); vector<vector<int>> result; if (size<4) return result; sort(nums.begin(),nums.end()); for(int i=0;i<size;i++) { if(i>0 && nums[i]==nums[i-1]) continue; //a int tempTarget1=target-nums[i]; for(int j=i+1;j<size;j++) { if(j>i+1 && nums[j]==nums[j-1]) continue; //b int tempTarget2=tempTarget1-nums[j]; int front=j+1,rear=size-1; while(rear>front) { if(front>j+1 && nums[front] == nums[front-1]) //c { front++; continue; } if(rear<size-1 && nums[rear] == nums[rear+1]) //d { rear--; continue; } int sum=nums[rear]+nums[front]; if(sum>tempTarget2) rear--; else if(sum<tempTarget2) front++; else { vector<int> temp; temp.push_back(nums[i]); temp.push_back(nums[j]); temp.push_back(nums[front]); temp.push_back(nums[rear]); result.push_back(temp); front++;rear--; } } } } return result; } };
注意几个关键的地方:a,b,c,d这样处理就可以避免重复。
相关文章推荐
- 【POJ1552】:Doubles
- mysql_dev关于sql服务器端理解
- Implement Hash Map Using Primitive Types
- iOS- KVC,KVO,NSNotification总结
- [转]Maven如何手动添加jar包到本地Maven仓库
- 巧妙获取数据库连接字符串
- [转]Maven如何手动添加jar包到本地Maven仓库
- 黑马程序员_BufferdReader 的原理及重写这个方法的主要功能包括带行号的输出
- HDU 1496 Equations(hash)
- Eclipse调试的一些小技巧
- Binder进程间通信机制的Service Manager组件响应Service组件的注册过程
- 大数据的核心
- 二分查找算法的C语言实现
- Java学习笔记———《单例模式的7种实现详解》
- struct 传输类中类时遇到的问题
- Angular.js指令
- 使用异步消息处理更新UI线程
- swt Tree 多列 multiple columns(Treetable) 获取每个treeitem值
- 如何限制对象只能建立在堆上或者栈上【转载】
- 《zw版·Halcon-delphi系列原创教程》cgal与opencv,Halcon