leetcode_4Sum、4Sum II
来源:互联网 发布:网络招生实战 丁丛 编辑:程序博客网 时间:2024/05/17 05:58
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.
class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> res = new ArrayList<>(); if(nums==null || nums.length<4) return res; 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 left = j+1; int right = nums.length-1; while(left<right){ if(nums[left]+nums[right]==target-nums[i]-nums[j]){ res.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right])); while(left<right && nums[left]==nums[left+1]) left++; while(left<right && nums[right]==nums[right-1]) right--; left++; right--; }else if(nums[left]+nums[right]>target-nums[i]-nums[j]){ right--; }else{ left++; } } } } return res; }}
4Sum就是在3Sum的外面在套一层循环就好了,需要注意的细节是循环的结束点以及跳过的值
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.
class Solution { public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); int count = 0; for(int i=0; i<A.length; i++){ for(int j=0; j<B.length; j++){ int sumAB = A[i]+B[j]; if(map.containsKey(0-sumAB)) map.put(0-sumAB,map.get(0-sumAB)+1); else map.put(0-sumAB,1); } } for(int k=0; k<C.length; k++){ for(int m=0; m<D.length; m++){ int sumCD = C[k]+D[m]; if(map.containsKey(sumCD)) count+=map.get(sumCD); } } return count; }}
4Sum II是利用hashmap,首先利用两个for循环将前两个数组相加的和(这里转换为0-相加的和作为hashmap的键值),如果另外两个数组相加的和在在这个map中,说明这四个数字相加的和为0。
- leetcode_4Sum、4Sum II
- Leetcode_4sum
- LeetCode_4Sum
- 454. 4Sum II
- 454. 4Sum II
- 454. 4Sum II
- 4Sum II
- 454. 4Sum II
- 4Sum II
- leetcode_middle_18_454. 4Sum II
- 454. 4Sum II
- 454. 4Sum II
- leetcode454~4Sum II
- 4Sum II
- 454. 4Sum II
- 454. 4Sum II
- [LeetCode] 4Sum II
- 454. 4Sum II
- unity在webgl端 输入框无法输入中文和中文显示问题的解决
- SEO新手不知道每天做什么,看了你就知道
- mycat分布式mysql中间件(入门)
- 面向对象笔记
- C#基础系列——反射笔记
- leetcode_4Sum、4Sum II
- Vivado 时序问题简析
- SVG基础六:椭圆
- VC调试信息的输出
- OpenGL——理解SSAO
- 医疗行业安全建设方案
- node.js ejs的视图模块引擎
- js取得文档的高度和宽度
- Docker 组件如何协作?- 每天5分钟玩转Docker容器技术(8)