LeetCode进阶之路(4Sum)
来源:互联网 发布:papago翻译软件 编辑:程序博客网 时间:2024/05/21 13:21
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类似,求4个的和。所以可以直接套用3sum的算法,但是这种解法超过时间限制。有点晚了,先贴上代码,明天有空研究。下面的两个方法还是直接用的3Sum,没做修改。
7.19更新:重新修改3sum、2sum算法,整理了一下逻辑。
public class Solution { List<List<Integer>> list2 = new ArrayList<List<Integer>>(); public List<List<Integer>> fourSum(int[] nums, int target) {if(nums == null || nums.length < 4) return list2;Arrays.sort(nums);for(int i = 0; i < nums.length - 3;i++) {if(i > 0&& nums[i] == nums[i-1])continue;int[] num = Arrays.copyOfRange(nums, i+1, nums.length);threeSum(num, target-nums[i], nums[i]);}return list2;}public void threeSum(int[] nums, int target, int startNum){if(nums == null || nums.length < 3) return ;Arrays.sort(nums);for(int i = 0;i < nums.length-2;i++) {if(i > 0 && nums[i] == nums[i-1])continue;int[] num = Arrays.copyOfRange(nums, i+1, nums.length);twoSum(num, target-nums[i], nums[i], startNum);}}public void twoSum(int[] nums, int target, int n, int startNum) {int left = 0;int right = nums.length -1;while(left < right) {if(left> 0 && nums[left-1] == nums[left]){left++;continue;} if(right < nums.length -1 && nums[right + 1] == nums[right]){right--;continue;}if(nums[left] + nums[right] == target) {List<Integer> l = new ArrayList<Integer>();l.add(nums[left]);l.add(nums[right]);l.add(n);l.add(startNum);list2.add(l);left++;right--;}else if(nums[left] + nums[right] < target) {left++;}else {right--;}}}}
每天下班回来都快10点了,洗澡弄完都11点多,有时候累的真想直接躺下睡觉,但是一想,现在不努力,以后还会有机会吗?咬咬牙还是把这个任务完成了再睡,至少熟悉下题目,思考一会。
0 0
- LeetCode进阶之路(4Sum)
- LeetCode进阶之路(3Sum)
- LeetCode进阶之路(3Sum Closest)
- LeetCode进阶之路(Combination Sum)
- LeetCode进阶之路( Combination Sum II)
- LeetCode进阶之路(Minimum Path Sum)
- leetcode之4Sum
- 【Leetcode】之4Sum
- leetcode之4Sum
- LeetCode之18---4Sum
- Leetcode 之 4Sum II
- leetcode 之4Sum问题
- LeetCode之4Sum II
- 【Leetcode】4Sum (Sum)
- LeetCode进阶之路(twoSum)
- LeetCode进阶之路(ZigZag Conversion)
- LeetCode进阶之路(Reverse Integer)
- LeetCode进阶之路(Reverse Integer)
- HDU 2448 Mining Station on the Sea(floyd+KM)
- java网络编程
- 206. Reverse Linked List
- git快速入门(一)git环境配置
- Java个人理解之时间的使用
- LeetCode进阶之路(4Sum)
- 野指针与野指针的避免
- 欢迎使用CSDN-markdown编辑器
- Java-static
- 走遍欧洲 —— 匈牙利、奥地利
- Hardware Acceleration(硬件加速)
- nested exception is java.lang.NoClassDefFoundError: com/mchange/v2/ser/Indirector
- 第24日:实施质量保证 和 组建项目团队
- ruby爬虫日记1