3Sum

update Aug 19, 2017 14:12

LeetCodearrow-up-right

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]
]

Basic Idea:

从左到右,选择每个数字作为第一个数,然后针对每种情况,执行一次 2 pointers 求 2 sum 的操作。

但是要注意去重。去重的时候注意三点:

  1. 首先对nums进行排序,从小到大;

  2. 每次求 two sum 的起始位置(left的位置)应该是 i+1,即当前第一个数之后的那个数;

  3. 在每次出现可行解之后,要用while循环让left和right向中间同时移动,跳过所有重复组合;

Java Code:

_Updated: 10/13/2024_

2 Sum, with HashMap

Last updated