[LeetCode]3Sum
来源:互联网 发布:如何查看ubuntu版本 编辑:程序博客网 时间:2024/06/05 10:52
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
以一个数为target然后循环求得是否有两个数等于之,while循环里是关键算法。
public class Solution { public List<List<Integer>> threeSum(int[] num) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if(num == null||num.length<3){ return res; } Arrays.sort(num); for(int i=0;i<num.length-2;i++){ int target = -num[i]; int left = i+1; int right = num.length - 1; while(left<right){ if(target == num[left]+num[right]){ List<Integer> lists= new ArrayList<Integer>(); lists.add(num[i]); lists.add(num[left]); lists.add(num[right]); if(res.isEmpty()||!res.contains(lists)){ res.add(lists); } left++; right--; }else if(target > num[left]+num[right]){ left++; }else{ right--; } } } return res; }}
0 0
- 【Leetcode】3Sum (Sum)
- Leetcode:2Sum,3Sum
- 【Leetcode】3Sum Closest (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- LeetCode: 3Sum
- LeetCode: 3 Sum Closest
- leetcode - 3 Sum
- leetcode - 3 sum closest
- leetcode 3Sum
- leetcode 3Sum Closest
- LeetCode: 3Sum
- 关于编译activemq-cpp新的感受
- linux下提示bash:command not found
- Python 直接插入排序
- Spring事务传播特性
- onSaveInstanceState() onRestoreInstanceState() onRetainNonConfigurationInstance() getLastNonConfigur
- [LeetCode]3Sum
- CABasicAnimation
- 吐槽一下项目中的代码坏味道:滥用java常量
- 如何实现全局识别摇晃手势
- 程序编译中的字节对齐
- C结构体之位域(位段)
- linux 启动新安装的Apache时Could not reliably determine the server's fully qualified domain name
- 读书札记-2013年12月
- iOS小知识点总结(二)