一、问题描述
Given an array nums
of n integers, are there elements a, b, c in nums
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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
二、解题思路
3 Sum问题可以转化为2 Sum问题(类似4 Sum问题可以转化为3 Sum)。这类问题最优解的时间复杂度为O(n*(k-1))。即:2 Sum最优复杂度为O(n),3 Sum最优为O(n * n)。
对于2 Sum有两种解题思路:
①先排序,然后用left和right分别指向开头和结尾,之后计算和。同时根据情况移动即可。感觉这种方法像是快排。时间复杂度是:O(NlogN);
②就是利用unordered_map(底层为哈希表),查找一个数为线性时间,这样的话一次遍历即可找到,所以复杂度就降低为