Three Sum with duplicated values

2. 描述

给出一个有n个元素的数组S,S中是否有元素a,b,c满足a+b+c=0?找出数组S中所有满足条件的三元组。注意:

  1. 三元组(a、b、c)中的元素必须按非降序排列。(即a≤b≤c)

  2. 解集中不能包含重复的三元组。

示例1

输入:

复制返回值:

复制

示例2

输入:

复制返回值:

3. 思路

  1. sort array

  2. iterate every element num[i]

  3. binary search for the remaining element to check if two sum to target = 0- num[i] exist

  4. skip all duplicated values once the first element found to avoid duplicated results

  5. Time: O(nlogn) for sorting O(n ) for the first loop, O(n) for binary search in worst case, so O(n^2 + nlogn) = O(n^2)

  6. Space O(1)

4. Coding

Last updated

Was this helpful?