Given an array of integers nums and an integer target, return an array of arrays containing all unique triplets that add up to target.
Each returned triplet must be in ascending order, and the final result must not contain duplicate triplets.
You may assume nums has at least 3 elements.
Example:
Input:
nums = [-1, 0, 1, 2, -1, -4]
target = 0
Output:
[[-1, -1, 2], [-1, 0, 1]]
这题就是扩展版的 三数之和 3Sum。
思路非常固定、也是 Tesla 和 FAANG 经常考的套路:
- 先排序
排序是为了让三元组自动升序,也方便去重。 - 枚举第一个数 i
nums[i]确定后,后面就变成“两数之和”。 - 双指针 l, r 找另外两个数
寻找nums[l] + nums[r] = target - nums[i] - 注意去重!
i不能和前一个重复l往右走要跳过相同值r往左走也要跳过相同值
时间复杂度 O(n²),是最优解。
这题就是看你双指针写得熟不熟、去重有没有经验。
VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括 Tesla、Google、Amazon、Citadel、SIG 等,提供实时答案助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备公司的面试,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。