4Sum:带重复数组取值求和
来源:互联网 发布:三国之数据辅助103 编辑:程序博客网 时间:2024/05/22 12:59
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]]思路:由于有重复不能dfs遍历,所以得排序,比3sum多一重循环。代码参考:https://leetcode.com/problems/4sum/discuss/
public class Solution {public List<List<Integer>> fourSum(int[] num, int target) { ArrayList<List<Integer>> ans = new ArrayList<>(); if(num.length<4)return ans; Arrays.sort(num); for(int i=0; i<num.length-3; i++){ if(num[i]+num[i+1]+num[i+2]+num[i+3]>target)break; //first candidate too large, search finished if(num[i]+num[num.length-1]+num[num.length-2]+num[num.length-3]<target)continue; //first candidate too small if(i>0&&num[i]==num[i-1])continue; //prevents duplicate result in ans list for(int j=i+1; j<num.length-2; j++){ if(num[i]+num[j]+num[j+1]+num[j+2]>target)break; //second candidate too large if(num[i]+num[j]+num[num.length-1]+num[num.length-2]<target)continue; //second candidate too small if(j>i+1&&num[j]==num[j-1])continue; //prevents duplicate results in ans list int low=j+1, high=num.length-1; while(low<high){ int sum=num[i]+num[j]+num[low]+num[high]; if(sum==target){ ans.add(Arrays.asList(num[i], num[j], num[low], num[high])); while(low<high&&num[low]==num[low+1])low++; //skipping over duplicate on low while(low<high&&num[high]==num[high-1])high--; //skipping over duplicate on high low++; high--; } //move window else if(sum<target)low++; else high--; } } } return ans;}
阅读全文
0 0
- 4Sum:带重复数组取值求和
- 3Sum:带重复数组中取三个元素求和为零
- Combination Sum:非重复数组中选取若干元素求和等于给定值
- Combination Sum II:允许重复的数组中选取若干元素使和为某一给定值
- hdu 3874 树状数组 成段不重复求和
- Combination Sum II 全排列求和无重复
- 求和 sum
- sum求和
- iOS 【KVC的拓展-key&keyPath区别/修改私有属性/取值/数组求和&平均值】
- PHP取数组中几个数值求和等于指定值的算法
- LeetCode 303. Range Sum Query - Immutable(数组求和)
- [数组]汕头市选2012初中组】求和(sum)
- 判断数组中包含重复数(大数中取重复)
- mysql不重复字段值求和
- 解析mysql不重复字段值求和
- LeetCode—*Combination Sum II(DFS算法C数组中有重复值)
- 初始一个取值范围为[1,10]随机数组,去掉重复.
- 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)
- ElasticSearch _xpack用户管理
- dialog常用
- MPU9250九轴姿态解算开发小结
- 数据结构之课程大总结
- scrapy安装win32api,找不到包解决方法
- 4Sum:带重复数组取值求和
- [Python]
- PHP与JS跨域请求
- CentOS6.5中安装JDK
- Java获取Properties文件中值的方法
- Java反射实战
- 国家公务员考试之证监会计算机类
- 创投日报:12月13日收录投融资项目23起
- 10G多通道带内FEC波分复用传输设备解决方案