58.4Sum-四数之和(中等题)
来源:互联网 发布:linux如何安装bind 编辑:程序博客网 时间:2024/05/16 12:52
四数之和
题目
给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。
注意事项
四元组(a, b, c, d)中,需要满足a <= b <= c <= d
答案中不可以包含重复的四元组。样例
例如,对于给定的整数数组S=[1, 0, -1, 0, -2, 2] 和 target=0. 满足要求的四元组集合为:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)题解
57.3Sum-三数之和(中等题)的难度升级版,思路完全一致。
public class Solution { /** * @param numbers : Give an array numbersbers of n integer * @param target : you need to find four elements that's sum of target * @return : Find all unique quadruplets in the array which gives the sum of * zero. */ public ArrayList<ArrayList<Integer>> fourSum(int[] numbers, int target) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); Arrays.sort(numbers); for (int i=0;i<numbers.length-3;i++) { if (i!=0 && numbers[i] ==numbers[i-1]) { continue; } for (int j=i+1;j<numbers.length-2;j++) { if (j != i+1 && numbers[j] ==numbers[j-1]) { continue; } int start = j+1; int end = numbers.length-1; while (start < end) { int sum = numbers[i] + numbers[j] + numbers[start] + numbers[end]; if (sum == target) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(numbers[i]); list.add(numbers[j]); list.add(numbers[start]); list.add(numbers[end]); result.add(list); start++; end--; while (start < end && numbers[start] == numbers[start-1]) { start++; } while (start < end && numbers[end] == numbers[end+1]) { end--; } } else if (sum < target) { start++; } else { end--; } } } } return result; }}
Last Update 2016.9.30
0 0
- 58.4Sum-四数之和(中等题)
- 56.Two Sum-两数之和(中等题)
- 57.3Sum-三数之和(中等题)
- 59.3Sum Closest-最接近的三数之和(中等题)
- 4Sum 四数之和
- LeetCode 18. 4Sum(四数之和)
- [LeetCode] 4Sum 四数之和解法(本算法n数之和都能解)
- Leetcode: 18. 4Sum 四数之和
- 90.k Sum II-k数和 II(中等题)
- Two Sum(两数之和)
- LeetCode-Two Sum(两数之和)
- 1、Two Sum(两数之和)
- 三个数之和(3sum)
- 题目:四数之和
- 四数之和
- lintcode-- 四数之和
- Leetcode #18 4Sum 四数之和 解题小节+K-Sum思想
- LintCode两数之和,三数之和,四数之和
- AbstractFactory_Level6
- mybatis入门
- 大连首闻grid二次开发增强文档
- HDU - 1032 The 3n + 1 problem
- 轮播图片
- 58.4Sum-四数之和(中等题)
- 深度学习知识库精华+图谱一览
- 观察者模式——解耦利器
- android studio 分享到github 以及 出错
- Leetcode 94 Binary Tree Inorder Traversal
- Codeforcs--486C------Palindrome Transformation思维题
- 特殊的日子
- fzu2150 Fire Game bfs
- 下一秒的日期与时间