4Sum
2015-10-08 21:15
260 查看
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.
定好左右两个游标,中间两个游标移动
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)
package com.rust.cal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FourSum { public static List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> res = new ArrayList<List<Integer>>(); Arrays.sort(nums); int len = nums.length; for (int i = 0; i < len - 3; i++) { if (i > 0 && nums[i] == nums[i-1]) continue; for (int j = len - 1; j > i + 2; j--) { if (j < len - 1 && nums[j] == nums[j+1]) continue; int side = nums[i] + nums[j]; int left = i + 1; int right = j - 1; while (left < right) { int inner = nums[left] + nums[right]; if (side + inner == target) { List<Integer> singleAns = new ArrayList<Integer>(); singleAns.add(nums[i]); singleAns.add(nums[left]); singleAns.add(nums[right]); singleAns.add(nums[j]); res.add(singleAns); while (left < right && nums[left] == nums[left+1]) left++; //look forward while (left < right && nums[right] == nums[right-1]) right--; //skip the same number in nums[] left++; right--; } else if (inner + side > target){ right--; } else { left++; } } } } return res; } public static void main(String args[]){ List<List<Integer>> res = new ArrayList<List<Integer>>(); int[] nums = {-5,5,4,-3,0,0,4,-2}; int target = 4; res = fourSum(nums, target); /*output*/ for (int i = 0; i < nums.length; i++) { System.out.print(nums[i] + " "); } System.out.println(); System.out.println(res.size()); for (int i = 0; i < res.size(); i++) { for (int j = 0; j < res.get(i).size(); j++) { System.out.print(res.get(i).get(j) + "\t"); } System.out.println(); } } }
相关文章推荐
- ocp-212
- mysql中profile用法
- Attribute注解
- C语言基础知识
- ocp-211
- 【ShancoLove】带你看数据结构——第三课:线性表链式结构(单链表)
- C++ Primer const变量
- 在两个activity之间传送数据
- 万能药水(贪心)
- React Native入门遇到的一些问题
- 智能车学习(五)—— dac学习
- RHCE7 管理II-5管理进程的优先级
- 常用的开源游戏服务器框架
- ocp-210
- 剑指offer—把字符串转换成整数
- 匿名内部类和内部类
- 【读书笔记】GCD-网络编程要不要使用GCD
- XSS跨站脚本攻击剖析与防御
- 【读书笔记】GCD-网络编程要不要使用GCD
- Codeforces Round #324 (Div. 2)C. Marina and Vasya set