题目在这里: https://leetcode.com/problems/3sum/

【标签】 Array; Two Pointers

【个人分析】

老实交待,这个题卡半天,第一次做不会,抄别人的。过了很久,第二次做,还是不会……。好几次都是Time Limited Error。在看过正确答案之后,才知道是用的Two Pointers + sort 做的优化。

  怎么优化? 简单说,就是通过 排序 + 跳过重复(利用Two Pointers) 来达到题目中避免 duplicates的要求。

  核心思路: 我们给最终的由3个数组成的小数组叫 triplet。

1. 先锁定triplet中的第一个数字的index为 i (Line 12),

2. 然后我们希望从 [ nums[i + 1], nums[end]] 中找到两个数字,使得两个数字的和为 (0 - nums[i])

  关键步骤:1. 在锁定第一个数字index的时候,跳过所有重复的数字 (Line 16处)。直到我们找到下一个不重复的数字作为triplet中的第一个数字

2. 在从[nums[i + 1], nums[end]]中找两个数字的时候,利用left pointer, right pointer。如果 left, right两个数的和比 twoSumTarget (Line 39)

小的话,只能通过将left pointer向右移动,来使得left + right的和更大一些,从而更接近twoSumTarget。

【一点心得】

  在O(N^2)的算法中,考虑加入O(NlgN) 的排序操作。特别是遇到需要去除重复的时候,利用排序 + Two Pointers 来达到 HashSet的效果。

 public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
int len = nums.length;
if (len < 3) {
return result;
} Arrays.sort(nums); // for all number that can be the 1st number of triplet
for (int i = 0; i < len - 1; i++) {
int firstNumber = nums[i]; // skip all duplicated first number
if (i == 0 || firstNumber != nums[i - 1]) { int leftIndex = i + 1;
int rightIndex = len - 1;
int twoSumTarget = 0 - firstNumber; // try to find two numbers that sum up to twoSumTarget
while (leftIndex < rightIndex) {
int twoSum = nums[leftIndex] + nums[rightIndex];
if (twoSum == twoSumTarget) {
// one valid triplet found!!
result.add(Arrays.asList(firstNumber, nums[leftIndex], nums[rightIndex]));
// skip duplicated nums[leftIndex]
while (leftIndex < rightIndex && nums[leftIndex] == nums[leftIndex + 1]) {
leftIndex++;
}
// skip duplicated nums[rightIndex]
while (leftIndex < rightIndex && nums[rightIndex] == nums[rightIndex - 1]) {
rightIndex--;
}
// move to next non-duplicates
leftIndex++;
rightIndex--;
} else if (twoSum < twoSumTarget) {
// move left towards right to
// make twoSum larger to get closer to twoSumTarget
leftIndex++;
} else {
rightIndex--;
}
} }
} return result;
}
}

[Leetcode][015] 3Sum (Java)的更多相关文章

  1. 【JAVA、C++】LeetCode 015 3Sum

    Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all un ...

  2. [Leetcode]015. 3Sum

    public class Solution { public List<List<Integer>> threeSum(int[] num) { Arrays.sort(num ...

  3. [Leetcode][016] 3Sum Closest (Java)

    题目: https://leetcode.com/problems/3sum-closest/ [标签]Array; Two Pointers [个人分析] 这道题和它的姊妹题 3Sum 非常类似, ...

  4. [LeetCode] 259. 3Sum Smaller 三数之和较小值

    Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 < ...

  5. No.015 3Sum

    15. 3Sum Total Accepted: 131800 Total Submissions: 675028 Difficulty: Medium Given an array S of n i ...

  6. 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)

    转自  http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...

  7. LeetCode 15 3Sum [sort] <c++>

    LeetCode 15 3Sum [sort] <c++> 给出一个一维数组,找出其中所有和为零的三元组(元素集相同的视作同一个三元组)的集合. C++ 先自己写了一发,虽然过了,但跑了3 ...

  8. LeetCode--No.015 3Sum

    15. 3Sum Total Accepted: 131800 Total Submissions: 675028 Difficulty: Medium Given an array S of n i ...

  9. LeetCode 16. 3Sum Closest(最接近的三数之和)

    LeetCode 16. 3Sum Closest(最接近的三数之和)

随机推荐

  1. PHP+mysql统计排名第几位

    正在开发积分系统!其中有一项数据是显示用户积分排名?一下子想不到太好的办法! 最简的情况是统一某一字段的积分数据排名?比如积分字段,里面存的整数! 如何排名?或者说如何获得他在排序中的序列位次呢? s ...

  2. Android 每隔3s更新一次title

    MainActivity.java public class MainActivity extends Activity { private static int i=0; @Override pro ...

  3. AD学习笔记----PCB设计

    1.重新设置板子的形状 Design ---->Board Shape---->Redefine Board Sharp 2.通过Board Options 对板子进行设置 3.添加一个新 ...

  4. delphi 程序窗体及控件自适应分辨率(通过ComponentCount遍历改变字体大小以及上下左右)

    unit untFixForm; interface uses Classes, SysUtils, Controls, Forms; type TFontedControl = class(TCon ...

  5. GitHub 如何基於 Node.js 和 Chromium 開發 Atom?

    看到回答里, 多数都没有回答到点子上, 还有些给了非常主观的意见而没有给出实际结论和分析过程. 题主的问题有四个: 1. Github 如何基于 Node.js 和 Chromium 开发 Atom? ...

  6. 点击类名方法名如何连接到相应的Android源代码

    . 找到Android SDK所在路径 “D:\androidDev\android-sdk-windows\” . 在该目录下选择platforms到 “D:\androidDev\android- ...

  7. perl dbi 测试 mysql wait_timeout

    The number of seconds the server waits for activity on a noninteractive connection before closing it ...

  8. ASP.NET获取IP的6种方法(转载于LanceZhang's Tech Blog)

    服务端: //方法一 HttpContext.Current.Request.UserHostAddress; //方法二 HttpContext.Current.Request.ServerVari ...

  9. [Tips]ASP.NET MVC 发布到服务器后Model中属性相关的Attribute失效

    Asp.net MVC4 开发的项目,发布到真实环境环境后Model中的一个属性设置的了Attribute,但是这些Attribute都失效. 经过对比和坚持代码发现控制长度的Attribute使用错 ...

  10. POJ3729 Facer’s string 后缀数组

                                                                                                      Fa ...