Leetcode 15. 3sum
来源:互联网 发布:cf陈子豪刷枪软件 编辑:程序博客网 时间:2024/06/17 14:28
@author stormma
@date 2017/11/03
生命不息,奋斗不止!
题目
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: 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]]
思路分析
刚开始我使用确定两个数去二分查找另外一个数,这样时间复杂度是O(N^2long N),但是有个问题就是不好去重,这个着实让我很纠结,然后思路一下被限制了。查看leetcode discuss之后,看到人家的答案豁然开朗。
我们换个思路,这次确定一个值,然后two pointer去查找另外两个元素,把sum = 0的全部添加进来,然后确定下一个元素的时候,我们跳过和之前一样的元素,这样时间复杂度O(N^2),而且去重还贼简单(看了别人的答案,我反手给自己一巴掌,实在太智障)。
- for i 0 to length - 2
- two pinter查找sum = 0 - nums[i]如果相等,添加答案,并且skip重复的元素
- 如果不相等,判断与0 - nums[i]的大小,然后移动指针即可
代码实现
static class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> ans = new ArrayList<>(); if (nums.length < 3) { return ans; } Arrays.sort(nums); for (int i = 0; i < nums.length - 2; i++) { // the min elemment > 0, break if (nums[i] > 0) { break; } // skip repeat element if (i > 0 && nums[i] == nums[i - 1]) { continue; } int low = i + 1, high = nums.length - 1, target = 0 - nums[i]; while (low < high) { if (target < nums[low] + nums[high]) { high--; } else if (target > nums[low] + nums[high]) { low++; } else { ans.add(Arrays.asList(nums[i], nums[low], nums[high])); //eg: -2 0 0 1 1 2 2 and skip repeating elements, and their sum equals target while (low < high && nums[low + 1] == nums[low]) { low++; } while (low < high && nums[high - 1] == nums[high]) { high--; } low++; high--; } } } return ans; } }
代码很简单,相信你一看就懂,实在不懂,就再看一遍。
阅读全文
0 0
- LeetCode 15. 3Sum
- LeetCode --- 15. 3Sum
- [Leetcode] 15. 3Sum
- 【LeetCode】15. 3Sum
- 【leetcode】15. 3sum
- 【leetcode】15. 3Sum
- [leetcode] 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- Leetcode 15. 3Sum
- LeetCode - 15. 3Sum
- [LeetCode]15. 3Sum
- Leetcode 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- 【leetcode】15. 3Sum
- Leetcode - 15. 3Sum
- docker教程详解
- netstat 指令详解
- 常见面试排序: http://blog.csdn.net/pi9nc/article/details/12220851
- android armhf ettercap 安装
- Tensorflow深度学习框架在CentOS 7上的安装
- Leetcode 15. 3sum
- JAVA设计模式之命令模式
- day6总结
- 隔离装置传输文件
- 机房之完结
- 人脸识别-常用数据库
- WebApi实现验证授权Token,WebApi生成文档等
- 计算数组的小和
- AI笔记