[Leetocde] 4Sum (Java)
来源:互联网 发布:python搭建webservice 编辑:程序博客网 时间:2024/06/06 14:17
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:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- 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)
比3sum多了一层循环O(n3),没想到更简单的办法
public class Solution { public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();Set<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>();Arrays.sort(num);for(int i=0;i<num.length-3;i++){for(int j=i+1;j<num.length-2;j++) {int a = num[i];int b = num[j];int start = j+1;int end = num.length-1;while(start<end){int c = num[start];int d = num[end];if(a+b+c+d==target){ArrayList<Integer> temp = new ArrayList<Integer>();temp.add(a);temp.add(b);temp.add(c);temp.add(d);set.add(temp);start++;end--;}else if(a+b+c+d<target){start++;}else {end--;}}}}res.addAll(set);return res; }}
0 0
- [Leetocde] 4Sum (Java)
- Length of Last Word leetocde java
- 4Sum Java
- 4Sum (Java)
- 4Sum leetCode Java
- [LeetCode][Java] 4Sum
- LeetCode : 4Sum [java]
- leetcode 4Sum(Java)
- 4 Sum leetcode java
- (java)求3sum和4sum
- Leetocde: Palindrome Partitioning II
- [leetocde] Roman to Integer
- leetocde banlanced binary tree
- [Leetocde]Missing Ranges
- 【leetocde】179. Largest number
- Leetocde : Rotate List
- LeetCode – 4Sum (Java)
- [leetcode-18]4Sum(java)
- 实时监听js改变value,跨浏览器支持
- Presenting view controllers on detached view controllers is discouraged
- 有效删除CI框架中URL中的index.php
- 指针的大小
- print 格式化输出
- [Leetocde] 4Sum (Java)
- UVA 1330 - City Game(扫描方法 | 单调栈维护)
- GeoServer的特点
- Java杂知识点
- java代码中使用数据库的方法
- C#学习6(动态更新状态栏信息)
- 企业如何通过网站带来收益呢?
- 解题笔记(40)——第1-39篇合集
- ubuntu下NFS配置