leetCode 18.4Sum (4数字和) 解题思路和方法
2015-07-06 16:00
351 查看
4Sum
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是相关的题,此题转换成b+c+d = target - a =k的3Sum。
具体方法和思路见如下代码:
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是相关的题,此题转换成b+c+d = target - a =k的3Sum。
具体方法和思路见如下代码:
public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> list = new ArrayList<List<Integer>>(); int len = nums.length; if(len <= 3)//长度不足,直接返回 return list; Arrays.sort(nums);//排序 //开始循环 for(int i = 0; i < len - 2; i++){ //如果target> 0 且nums[i]>target,则剩余数组相加不可能=target if((target > 0 && nums[i] > target) || (target < 0 && nums[len-1] < target)) break; if(i > 0 && nums[i] == nums[i-1])//消除重复 continue; //由a+b+c+d = t 转换成b + c + d = t - a int a = target - nums[i]; for(int j = i + 1; j < len - 1;j++){ if((a > 0 && nums[j] > a) || (a < 0 && nums[len-1] < a))//如果nums[j]>a,则剩余数组相加不可能=a break; if(j > i+1 && nums[j] == nums[j-1]) continue; int m = j+1; int n = len - 1; while(m < n){ int k = nums[j] + nums[m] + nums ; if(k == a){ List<Integer> al = new ArrayList<Integer>(); al.add(nums[i]); al.add(nums[j]); al.add(nums[m]); al.add(nums ); list.add(al); m++; n--; while(m < n && nums[m] == nums[m-1]) m++; while(m < n && nums == nums[n+1]) n--; } else{//分情况改变位置标记 if(k < a) m++; else n--; } } } } return list; }
相关文章推荐
- oracle创建数据库命令
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- java数据结构和算法------希尔排序
- javascript实现可编辑的下拉框
- 关于时间同步
- nginx lua调用redis和mongo
- HDU 1001
- iOS 一个带动画的等待指示器
- pthread
- 文字滚动
- linux下vi操作 提示Found a swap file by the name
- Android 知识点
- 主机网卡发现所发送数据的目的IP和默认网关不在同一网段(网络)时,会丢弃该数据帧吗???
- jQuery入门:用包装集工作(Working with Selections)
- LeetCode151_Reverse Words in a String
- SQL Server死锁产生原因及解决办法 .
- WEB ajax笔记
- 思科PVLAN配置详解
- HTML5 bootstrap2网页兼容(支持IE10以下)
- 线段树详解(单点更新与成段更新\区间更新操作)