leetcode | 3Sum
来源:互联网 发布:ipad免越狱软件 编辑:程序博客网 时间:2024/06/06 07:27
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)
暴力解决法是每个人都能想到的,三层for循环,时间复杂度是O(n^3),而且还要处理重复的问题,显然不是题目想要的解法。
那能不能降到O(n^2)?排序算法的时间复杂度为O(nlgn),小于O(n^2),那么我们不妨先对数组排个序。
排序之后,我们就可以对数组用两个指针分别从前后两端向中间扫描了,如果是 2Sum,我们找到两个指针之和为target就OK了,那 3Sum 类似,我们可以先固定一个数,然后找另外两个数之和为第一个数的相反数就可以了。
代码不难,先看了再说。
public class Solution { public List<List<Integer>> list = new ArrayList<>(); public List<List<Integer>> threeSum(int[] nums) { if (nums == null || nums.length < 3) return list; Arrays.sort(nums); int len = nums.length; for (int i=0;i<nums.length-2;i++) { if(i>0&&nums[i]==nums[i-1]) continue; sum2(nums,i+1,len-1,-nums[i]); } return list; } public void sum2(int[] nums,int start,int end,int x) { int i = start; int j = end; while(i<j) { if(nums[i]+nums[j]==x) { List<Integer> tmp = new ArrayList<>(); tmp.add(nums[start-1]); tmp.add(nums[i]); tmp.add(nums[j]); list.add(tmp); while(i<j&&nums[i]==nums[i+1]) i++; while(i<j&&nums[j]==nums[j-1]) j--; i++; j--; } else if(nums[i]+nums[j]<x) { i++; } else { j--; } } }}
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
- 二分+树上乱搞 zoj3820 Building Fire Stations
- php addslashes()函数
- 单链表应用(一)逆置
- 比较幸运的收到了两份offer
- typedef和#define的用法与区别
- leetcode | 3Sum
- 解析Json数据并缓存图片到sdcard
- java中Map,List与Set的区别
- 【机器学习】加州理工学院公开课——机器学习与数据挖掘 1.学习问题
- C/C++基本输入输出函数
- BZOJ3784 树分治、RMQ~~
- iOS 开发之封装一个 sqlite3 数据库
- 第三次复习课--UI(完)
- JavaScript 函数参数传递到底是值传递还是引用传递 (精华)