leetcode 4Sum 难度系数3 3.9
2014-01-28 12:07
281 查看
Question:
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)
public class Solution { private ArrayList<ArrayList<Integer>> results; public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) { results = new ArrayList<ArrayList<Integer>>(); if (num.length < 4) { return results; } Arrays.sort(num); int length = num.length - 1; for (int i = 0; i <= length - 3; i++) { if (i != 0 && num[i] == num[i - 1]) { continue; } for (int j = i + 1; j <= length - 2; j++) { if (j != i + 1 && num[j] == num[j - 1]) { continue; } subFourSum(num, i, j, j + 1, length, target); } } return results; } private void subFourSum(int[] num, int i, int j, int first, int last, int target) { while (first < last) { int sum = num[i] + num[j] + num[first] + num[last]; if (sum > target) { last--; } else if (sum < target) { first++; } else if (sum == target) { ArrayList<Integer> result = new ArrayList<Integer>(); result.add(num[i]); result.add(num[j]); result.add(num[first]); result.add(num[last]); results.add(result); first++; last--; while (first < last && num[first] == num[first - 1]) { first++; } while (first < last && num[last] == num[last + 1]) { last--; } } } } }
相关文章推荐
- leetcode Sum Root to Leaf Numbers 难度系数2 2.26
- leetcode JAVA Minimum Path Sum 难度系数3 3.22
- leetcode JAVA Combination Sum 难度系数3 3.13
- leetcode Palindrome Number 2.4 难度系数2
- leetcode JAVA Permutations 难度系数3 3.14
- leetcode Roman to Integer 2.5 难度系数2
- leetcode JAVA Anagrams 难度系数3 3.15
- leetcode JAVA Restore IP Addresses 难度系数3 3.33
- leetcode JAVA Unique Binary Search Trees 难度系数3 3.34
- leetcode JAVA Reverse Words in a String 难度系数2-3?最新题151
- leetcode Remove Nth Node From End of List 2.7 难度系数2
- leetcode JAVA Unique Paths 2.14 难度系数2
- leetcode JAVA Maximum Subarray 难度系数3 3.17
- leetcode JAVA Validate Binary Search Tree 难度系数3 3.35
- leetcode Merge Two Sorted Lists 2.9 难度系数2
- leetcode Valid Number 2.15 难度系数2
- leetcode JAVA Jump Game 难度系数3 3.18
- leetcode JAVA Binary Tree Level Order Traversal 难度系数3 3.36
- leetcode Valid Parentheses 2.8 难度系数2
- leetcode Add Binary 2.16 难度系数2