18. 4Sum
来源:互联网 发布:js获取身份证号码 编辑:程序博客网 时间:2024/06/04 08:03
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: 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]]
题目大意:给定一个包含n个数的数组S,一个target,寻找数组中4个和为target的所有数列。
思路:根据3sum进行扩充。
代码:
package Array;import java.util.ArrayList;import java.util.Arrays;import java.util.List;/*** @Author OovEver* @Date 2017/11/28 10:10*/public class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> res = new ArrayList<>(); if (nums.length < 4) { return res; } Arrays.sort(nums); for (int i = 0; i < nums.length - 3; i++) {// 最前面四个数大于target,则不用判断,直接跳出循环 if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) { break; }// 第一个数和最后三个数和小于target,则在此区间,不可能有等于target得数,continue if (nums[i] + nums[nums.length - 1] + nums[nums.length - 2] + nums[nums.length - 3] < target) { continue; }// 跳过重复的数 if (i > 0 && nums[i] == nums[i - 1]) { continue; }// 同上 for(int j=i+1;j<nums.length-2;j++) { if (nums[j] + nums[j + 1] + nums[j + 2] > target - nums[i]) { break; }// 同上 if (nums[j] + nums[nums.length - 1] + nums[nums.length - 2] < target - nums[i]) { continue; } if (j > i + 1 && nums[j] == nums[j - 1]) { continue; } int low = j + 1; int high = nums.length - 1; while (low < high) { int sum = nums[i] + nums[j] + nums[low] + nums[high]; if (sum == target) { res.add(Arrays.asList(nums[i], nums[j], nums[low], nums[high])); while (low<high&&nums[low]==nums[low+1]) low++; while (low<high&&nums[high]==nums[high-1]) high--; low++; high--; } else if (sum < target) { low++; } else { high--; } } } } return res; }}
阅读全文
0 0
- 15. 3Sum 和 18. 4Sum
- LeetCode --- 18. 4Sum
- [Leetcode] 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- leetcode 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum LeetCode
- 18. 4Sum
- leetcode 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- Oracle EBS Interface/API(5)--AR Invoices 原创 2015年11月20日 09:24:21 1393 系统版本: RDBMS : 9.2.0.
- Mqtt协议:写在前面的简单介绍
- js正则验证数字,字母和下划线(至少包含其中两种,数字不能开头)
- GIT for mac
- jieba做中文分词
- 18. 4Sum
- Spring5学习(二)-spring projects之Spring Cloud Data Flow
- Drawable基础知识总结----drawable标签layer-list的使用
- 4. 数组、切片和映射(Go Tutorial)
- 给tomcat指定jdk
- 剑指offer之java篇之旋转数组(二)
- CodeForces 839D Winter is here (容斥原理)
- ngnix负载均衡配置
- 依赖注入(DI)和控制反转