18. 4Sum
来源:互联网 发布:java sort排序算法 编辑:程序博客网 时间:2024/04/26 01:56
题目:4Sum
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]]
同样的思路,用C语言怎么都是Runtime error,而JAVA的话就可以通过。
代码:
public class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { int i=0,j=0; List<List<Integer>> ret = new ArrayList<List<Integer>>(); Arrays.sort(nums); int length=nums.length; for(i=0;i<length-3;i++) { if(i>0 && nums[i]==nums[i-1]) continue; for(j=i+1;j<length-2;j++) { if(j>(i+1) && nums[j]==nums[j-1]) continue; int s=j+1; int e=length-1; while(s<e) { int sum=nums[i]+nums[j]+nums[s]+nums[e]; if(sum == target) { List<Integer> t=new ArrayList<Integer>(); t.add(nums[i]); t.add(nums[j]); t.add(nums[s]); t.add(nums[e]); ret.add(t); while(s<e && nums[s]==nums[s+1])s++; while(s<e && nums[e]==nums[e-1])e--; s++; e--; } else if(sum < target) { s++; } else { e--; } } } } return ret; }}
0 0
- 15. 3Sum 和 18. 4Sum
- LeetCode --- 18. 4Sum
- [Leetcode] 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- leetcode 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 18. 4Sum LeetCode
- 18. 4Sum
- leetcode 18. 4Sum
- 18. 4Sum
- 18. 4Sum
- 短时傅里叶变换原理解
- 20161105
- 顺序队列
- Android应用框架之Home程序(Launcher)
- bootstrap基本css样式按钮
- 18. 4Sum
- 2016 China CAD&CG 参会总结 -- day1
- hdu 5969 最大的位或【贪心】
- ubuntu16.04一步一步安装配置mpich
- Docker Hub简介及自动化构建镜像
- 【十九】微分动态规划
- 周六
- django的增删改查
- 内存管理