LeetCode OJ算法题(十七):4Sum
来源:互联网 发布:数据库的基本对象是 编辑:程序博客网 时间:2024/06/05 14:15
题目:
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一样,只是多一次循环而已,a[i] 和a[j]相加的条件变为target-a[k]-a[m]
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class No17_FourSum {public static void main(String[] args){System.out.println(fourSum(new int[]{1,0,-1,0,-2,2}, 0));}public static List<List<Integer>> fourSum(int[] num, int target) { List<List<Integer>> ret = new ArrayList<List<Integer>>(); if(num.length < 4) return ret;Arrays.sort(num);int k_pre = num[num.length-1]+1;for(int k=0;k<num.length-3;k++){if(num[k] == k_pre) continue;k_pre = num[k];int m_pre = num[num.length-1]+1;for(int m=k+1;m<num.length-2;m++){if(num[m] == m_pre) continue;m_pre = num[m];int i = m+1;int j = num.length-1;int i_pre = num[num.length-1]+1;int j_pre = num[num.length-1]+1;while(i<j){if(num[i]+num[j] < target-num[k]-num[m]){do{i++;}while(i<j && num[i] == i_pre);if(i<j)i_pre = num[i];continue;}if(num[i]+num[j] > target-num[k]-num[m]){do{j--;}while(i<j && num[j] == j_pre);if(i<j)j_pre = num[j];continue;}ArrayList<Integer> element = new ArrayList<Integer>();element.add(num[k]);element.add(num[m]);element.add(num[i]);element.add(num[j]);ret.add(element);i_pre = num[i];j_pre = num[j];do{i++;}while(i<j && num[i] == i_pre);do{j--;}while(i<j && num[j] == j_pre);if(i<j){i_pre = num[i];j_pre = num[j];}}}} return ret; }}
0 0
- LeetCode OJ算法题(十七):4Sum
- LeetCode OJ算法题(二十七):Implement strStr()
- LeetCode OJ算法题(一):Two Sum
- LeetCode OJ算法题(十五):3Sum
- LeetCode OJ算法题(十六):3Sum Closest
- LeetCode OJ算法题(三十八):Combination Sum
- LeetCode OJ算法题(三十九):Combination Sum II
- LeetCode OJ算法题(六十三):Minimum Path Sum
- LeetCode OJ:4Sum
- LeetCode OJ 4Sum
- LeetCode OJ-18-4Sum
- LeetCode OJ - 3Sum、3Sum Closest、4Sum
- LeetCode OJ 第1题 (Two Sum )
- LeetCode OJ 之 4Sum (”四个数的和“)
- LeetCode OJ算法题(四十五):Permutations
- LeetCode OJ算法题(四十八):Anagrams
- LeetCode OJ算法题(七十七):Combinations
- LeetCode OJ算法题(七十八):Subsets
- 常用的linux命令
- Linux常用命令
- iOS7布局适配兼容的一篇好文章!!必须转
- 解决eclipse闪退可能启动不了
- hdu1429
- LeetCode OJ算法题(十七):4Sum
- Visual Prolog 的 Web 专家系统 (9)
- 刘鹏计算广告学听课笔记 第二章:合约广告系统(二)
- 《FusionCharts学习及使用笔记》
- Centos中安装.SSH安装,配置以及使用
- hdu1885
- hdu 2119 Matrix 二分图 最小点覆盖
- 6个海盗抢到了100颗宝石,每一颗都一样的大小和价值连城。他们决定这么分:
- git配置和简单使用