leetcode 18. 4Sum
2016-05-05 17:00
295 查看
import java.util.ArrayList; import java.util.Arrays; import java.util.List; //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) public class Solution { public static void main(String[] args) { int[] a = {-1,2,2,-5,0,-1,4}; List<List<Integer>> result = fourSum(a,3); for(int i = 0;i<result.size();i++){ System.out.println(result.get(i)); } } public static List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> result = new ArrayList<List<Integer>>(); List<List<Integer>> result1 = new ArrayList<List<Integer>>(); for(int i = 0;i<nums.length;i++){ //降序排列 for(int j = i+1;j<nums.length;j++){ if(nums[i]<nums[j]){ int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } } } for(int i = 0;i<nums.length-3;i++){ //确定第一个数,后面三个数使用3sum程序 if(i>0&&nums[i] == nums[i-1]) continue; //若有两个相同则跳过 int[] num = new int[nums.length-i-1]; for(int j = i+1,k=0;j<nums.length;j++,k++){ //取当前数后面的数组 num[k] = nums[j]; } result = threeSum(num, target-nums[i]); for(int k = 0;k<result.size();k++){ result.get(k).add(nums[i]); //将3sum结果加入当前的数,成为4sum结果 } result1.addAll(result); //将每个数得到的3sum结果合并 } return result1; } public static List<List<Integer>> threeSum(int[] nums, int target) { List<List<Integer>> result = new ArrayList<List<Integer>>(); Arrays.sort(nums); for(int i = 0;i<nums.length-2;i++){ //遍历数组 int j = i+1; int end = nums.length-1; if(i>0&&nums[i] == nums[i-1]){ continue; } while(j<end){ //从当前元素之后的两头寻找与其之和为0的两个元素 if(nums[i]+nums[j]+nums[end] == target){ List<Integer> a = new ArrayList<Integer>(); a.add(nums[i]); a.add(nums[j]); a.add(nums[end]); result.add(a); while(nums[end-1] == nums[end]&&end>j){ //若有相同元素,则直接跳过 end--; } while(nums[j+1] == nums[j]&&j<end){ j++; } end--; j++; }else if(nums[i]+nums[j]+nums[end]>=target){ //若相加不为0,则根据情况调整两端位置 end--; }else{ j++; } } } return result; } }
相关文章推荐
- Redis3.0.5封装
- HTML5 Canvas游戏开发(四)lufylegend开源库件(下)
- Jmeter之Badboy录制脚本及简化脚本http请求(三)
- 如何使用PS制作橙色高光壁纸
- java生成图片验证码--公用
- 重新学习《C++Primer5》第9章-顺序容器
- Socket通信详细解析(附例子)
- 机械大楼电梯控制项目
- 浅谈Android事件分发机制(一)点击事件的传递规则
- mysql 修改账户密码
- uefi+gpt+ghost安装win7系统
- Java中throws和throw的区别讲解
- 高德地图导航中出现报空的情况
- 一步一步带你实现ListView动画展开布局, ExpandableLayout实现
- ref和out
- AFNetworking学习
- C++中的虚函数表
- Centos 6.5 命令记录
- jquery实现全选和全不选功能效果的实现代码【推荐】
- PKU 3275 Ranking the Cows 最短路 floyd