Leet Code 18 4Sum - 四个数的和等于给定值 - Java
2016-06-08 00:00
441 查看
摘要: Leet Code 18 4Sum - 四个数的和等于给定值 - Java
问题原始链接 https://leetcode.com/problems/4sum
给定长度为n的整数数组S,找到所有和等于指定值的四个元素。
注意:结果集中不能包含重复的元素组。
例如,给定数组 S = [1, 0, -1, 0, -2, 2],并且 target = 0。
结果集为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
问题原始链接 https://leetcode.com/problems/4sum
给定长度为n的整数数组S,找到所有和等于指定值的四个元素。
注意:结果集中不能包含重复的元素组。
例如,给定数组 S = [1, 0, -1, 0, -2, 2],并且 target = 0。
结果集为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
[code=language-java]public class Solution { public static List<List<Integer>> fourSum(int[] nums, int target) { if (nums == null || nums.length < 4) { return new ArrayList<List<Integer>>(); } List<List<Integer>> result = new ArrayList<List<Integer>>(); 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 k = j + 1; int l = nums.length - 1; while (k < l) { int sum = nums[i] + nums[j] + nums[k] + nums[l]; if (sum == target) { result.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l])); k++; l--; while (k < l && nums[k] == nums[k - 1]) { k++; } while (k < l && nums[l] == nums[l + 1]) { l--; } } else if (sum < target) { k++; } else { l--; } } } } return result; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解