15. 3Sum
# Medium
Two pointers problem + one fixed pointer.
One pointer starts from the beginning of the list, the other one starts from the end of the list. The fixed pointer represents the one of the three elements.
Solution:
Set one pointer
i
, from0
tolen(nums)-2
Set second pointer
j
, starting fromi+1
Set third pointer
k
, starting fromlen(nunms)-1
sum = nums[i] + nums[j] + nums[k]
If
sum == 0
, add the three elements to result, andj ++ & k --
; Ifsum > 0
,k --
; Ifsum < 0
,j ++
Stop condition: while
j < k
.In order to avoid duplication
If
nums[i] == nums[i-1]
, skip this index.Set result as
set
, set the list as aset
before adding it to the result. Becausenums
has been sorted, so don't need to consider duplication.
Last updated