Leetcode no. 18
2016-04-26 14:45
405 查看
18. 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)
public class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> list= new LinkedList<>(); if (nums.length<4) return list; Arrays.sort(nums); for (int i = 0; i < nums.length-3; i++) { if (i>0 && nums[i]== nums[i-1]) continue; for (int j = i+1; j < nums.length-2; j++) { if (j>i+1 && nums[j]== nums[j-1]) continue; int subtarget= target-nums[i]-nums[j]; int m= j+1, n= nums.length-1; while (m<n){ if (nums[m]+nums ==subtarget) { list.add(Arrays.asList(nums[i], nums[j], nums[m], nums )); while (m < n && nums[m] == nums[m + 1]) m++; while (m < n && nums == nums[n - 1]) n--; m++; n--; } else if (nums[m]+nums <subtarget) m++; else n--; } } } return list; } }
相关文章推荐
- 关于webview的常识
- C#版--简单工厂模式
- 科幻小说网1.0构思
- 阿里云centos配置postfix
- IOS 杂记
- 为什么日本德国没有一流互联网企业?
- 设计模式笔记——MVC模式
- 上传文件
- Node.js Error: listen EADDRNOTAVAIL
- 【转】CentOS: 开放80、22、3306端口操作
- win7系统关机提示"您可以安全地关闭计算机了"的故障原因及解决方法
- 第一篇
- userData IE
- 查看进程所占内存/proc/[pid]/statm踩坑记
- 如何安装DedeCMS V5.7
- java越来越重要
- [AapacheBench工具]web性能压力测试工具的应用与实践
- 文件创建时间、访问时间、修改时间
- MFC CString的L和_T
- ARM学习b,bl指令浅析