3Sum
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:
1 | Given array nums = [-1, 0, 1, 2, -1, -4], |
思路:三数求和,重点在于复杂度,能想到的枚举法,至少3层for循环嵌套,还得消除重复元素。
第一版算法无错但是超时的代码如下:
1 | class Solution { |
想到排序后的数组更有规律,方便操作,改进后的代码如下:
1 | class Solution { |