leetcode-18. 4Sum
2017-05-11 23:28
357 查看
https://leetcode.com/problems/4sum/#/description
问题描述:
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]
]
思路解析:
参考这两道题:
http://blog.csdn.net/u013275928/article/details/71440744
http://blog.csdn.net/u013275928/article/details/71698864
设立四个指针,注意边界由于是四个值,集合中可能有重复的元组出现,所以需要list的contains()来判断当前符合条件的元组是否在集合中出现过,若未出现则加进来。然后移动指针。
代码如下:
问题描述:
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]
]
思路解析:
参考这两道题:
http://blog.csdn.net/u013275928/article/details/71440744
http://blog.csdn.net/u013275928/article/details/71698864
设立四个指针,注意边界由于是四个值,集合中可能有重复的元组出现,所以需要list的contains()来判断当前符合条件的元组是否在集合中出现过,若未出现则加进来。然后移动指针。
代码如下:
public class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> result=new ArrayList<>(); if(nums==null || nums.length<4) { return result; } Arrays.sort(nums); for(int i=0;i<nums.length-3;i++ ) { for(int j=i+1;j<nums.length-2;j++) { int h=j+1; int k=nums.length-1; while(h<k) { int sum=nums[i]+nums[j]+nums[h]+nums[k]; if(sum==target) { // List<Integer> temp=new ArrayList<Integer>(); // temp.add(); if(!result.contains(Arrays.asList(nums[i],nums[j],nums[h],nums[k]))) { result.add(Arrays.asList(nums[i],nums[j],nums[h],nums[k])); } h++; k--; } else if(sum>target)k--; else h++; } } { } } return result; } }
相关文章推荐
- 【Leetcode】C# 18、4Sum
- leetcode 18 4Sum
- LeetCode18 - 4Sum
- Leetcode||18. 4Sum
- LeetCode 18 - 4Sum
- [LeetCode]18 4Sum
- leetcode-18 4Sum
- LeetCode_18---4SUM
- leetcode题解-18. 4Sum
- LeetCode 18. 4Sum
- LeetCode: 18. 4Sum
- Leetcode 18 4Sum
- leetcode 18. 4Sum
- leetcode 18 4Sum
- Leetcode 1. Two Sum & 15. 3Sum & 16. 3Sum Closest & 18. 4Sum
- LeetCode 18 4Sum
- LeetCode 18 4Sum
- Leetcode 18. 4Sum
- leetcode-18 4Sum
- LeetCode 18 4Sum