leetcode18 4sum
来源:互联网 发布:淘宝客服月总结 编辑:程序博客网 时间:2024/06/09 22:45
我的leetcode代码已放入github:https://github.com/gaohongbin/leetcode
题目:
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.
思路:
和3sum的思路差不多。这里只贴代码。
代码:
public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> list= new ArrayList<List<Integer>>(); if(nums==null || nums.length<4) return list; quickSort(nums,0,nums.length-1); int length=nums.length; int first=0; int two=1; int three=2; int four=3; while(first<length-3){ two=first+1; while(two<length-2){ three=two+1; four=length-1; while(three<four){ if(nums[three]+nums[four]>target-nums[first]-nums[two]) four--; if(nums[three]+nums[four]<target-nums[first]-nums[two]) three++; if(nums[three]+nums[four]==target-nums[first]-nums[two] && three<four){ List<Integer> listThree=new ArrayList<Integer>(); listThree.add(nums[first]); listThree.add(nums[two]); listThree.add(nums[three]); listThree.add(nums[four]); list.add(listThree); three++; while(three<four){ if(nums[three]==nums[three-1]) three++; if(nums[three]!=nums[three-1]) break; } } } two++; while( two<length-2 && nums[two-1]==nums[two] ) two++; } first++;while( first<length-3 && nums[first-1]==nums[first] )first++; } return list; } public static void quickSort(int[] nums,int low,int high){if(low>=high || nums==null)return ;int length=nums.length;int mid=nums[low];int i=low,j=high;while(i<j){while(nums[j]>mid && j>i)j--;nums[i]=nums[j];while(nums[i]<=mid && i<j)i++;nums[j]=nums[i];}nums[j]=mid;quickSort(nums,low,j-1);quickSort(nums,j+1,high);}
0 0
- [LeetCode18]4Sum
- LeetCode18:4Sum
- leetcode18 4sum
- LeetCode18:4Sum
- [LeetCode18]4Sum
- LeetCode18. 4Sum
- leetcode18. 4Sum
- leetcode18:4Sum
- leetcode18~4Sum
- LeetCode18. 4Sum
- leetcode18. 4Sum
- leetcode18. 4Sum
- leetcode18 4Sum
- leetcode18. 4Sum
- LeetCode18. 4Sum
- leetcode18:4Sum(15-10-6)
- Leetcode1.Two Sum+LeetCode15.3Sum+LeetCode18. 4Sum【K-Sum问题】
- leetcode18
- 新生记
- eclipse中文语言包 离线安装
- 可替代CSS3 transition和transform的jQuery插件
- phpmyadmin 配置文件权限错误,无法写入!
- 线性表的动态分配顺序存储结构
- leetcode18 4sum
- Hive静态分区表
- Linux中的静态库和动态库简介及生成过程示例
- 在Eclipse中使用JUnit4进行单元测试
- 2016求职小结
- 从驱动层分析android的Binder机制-android学习之旅(83)
- 绑定启动Service
- 【NOIP2015 11.2上午模拟】总结
- 黑马程序员——基础知识——面向对象