Problem
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.
1
2
3
4
5
6
7
8
9Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
给定一个数组, 在数组中查找元素a,b,c, 三个数满足a+b+c = 0; 找到所有符合条件的解. 但是不能包含重复解.
Solution
Analysis
因为数组中可能存在重复元素,导致解也有可能重复. 所以我们先对数组进行排序, 数组排序后,相等元素在位置上相邻. 所以我们可以对重复数字进行跳过.
问题的求解. 数组经过排序, 数组有序,然后固定一个元素, 再对剩下区间元素使用双指针进行遍历,查找. 如果找到后, 同时变更指针, 让它们跳过重复元素[会生成重复解]. 然后继续遍历. 循环条件是left < right.
3Sum, 固定一个数, 然后使用两个指针进行遍历查找,时间复杂度O(N * logN).
方法总结就是: 双指针+夹逼.
K-Sum: 外层k-2次循环, 内部使用双指针进行夹逼.
Code
1 | class Solution { |