LeetCode|4Sum
来源:互联网 发布:shopnc java 源码 编辑:程序博客网 时间:2024/06/06 17:44
题目
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: 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]
]
总结:2Sum、3Sum、4Sum、KSum都是一类算法题,这里最主要的是优化时间复杂度,首先必须将给定的数组进行排序,然后确定K-2个数,剩下的两个数适用前后指针去遍历,得到的结果与目标数进行比较。
public class Solution {/** * 思路:首先需要对数组进行排序,使用两个for循环确定前两个数的值,然后使用前后指针去遍历除这两个数之外的数字,使这四个数相加 * 然后与目标数进行比较。 * 注意点:当遇到两个相同的数字的时候,需要做一些处理。 * 时间复杂度:o(n^3) */ public List<List<Integer>> fourSum(int[] nums, int target) { if (nums == null) { return null; } List<List<Integer>> result = new ArrayList<>(); Arrays.sort(nums); for (int i = 0; i < nums.length; i++) { if (i != 0 && nums[i - 1] == nums[i]) continue; for (int j = i + 1; j < nums.length; j++) { if (j !=i+1 && nums[j - 1] == nums[j]) continue; int start = j + 1; int end = nums.length - 1; while (end > start) { int sum = nums[i] + nums[j] + nums[start] + nums[end]; if (sum > target) { end--; } else if (sum < target) { start++; } else { result.add(Arrays.asList(nums[i], nums[j], nums[start], nums[end])); while (start + 1 < nums.length && nums[start + 1] == nums[start]) start++; while (end - 1 > 0 && nums[end - 1] == nums[end]) end--; start++; end--; } } } } return result; }}
0 0
- 【Leetcode】4Sum (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- LeetCode: 4 Sum
- LeetCode: 4Sum
- LeetCode 4Sum
- Leetcode: 4SUM
- 【leetcode】 4 sum
- LeetCode 4Sum
- leetcode 44: 4Sum
- [Leetcode] 4 Sum [Unsolved]
- 【leetcode】4Sum
- LeetCode|Sum of Two Integers
- VMware vSphere
- JDK动态代理与Spring AOP
- LeetCode|Add Two Numbers
- AngularJS Directive 隔离 Scope 数据交互
- LeetCode|4Sum
- BZOJ 1336 & 1337 最小圆覆盖
- 用自己电脑做服务器发布Java项目到外网
- 欢迎使用CSDN-markdown编辑器
- 赛马网基本算法之--翻转数组
- c# 抽象方法:实现两个数的加、减、乘操作运算
- leetcode_add two nums
- 项目经理如何规划自己的时间
- opencv中Moments函数较为详细的介绍