Three Sum with duplicated values
Last updated
Last updated
给出一个有n个元素的数组S,S中是否有元素a,b,c满足a+b+c=0?找出数组S中所有满足条件的三元组。注意:
三元组(a、b、c)中的元素必须按非降序排列。(即a≤b≤c)
解集中不能包含重复的三元组。
输入:
复制返回值:
复制
输入:
复制返回值:
sort array
iterate every element num[i]
binary search for the remaining element to check if two sum to target = 0- num[i] exist
skip all duplicated values once the first element found to avoid duplicated results
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)
Space O(1)