题目难度:
medium
题目要求:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
算法流程:
1)考虑特殊情况,如果数组的长度小于3或者数组为null,则不存在符合要求的数组,返回【】;
2)先对数组进行排序(从小到大);
3)排序后:
如果nums[i]>0,因为排序后从小到大,所以不存在三个数相加为0;对于重复的元素,跳过,避免出现重复解;令左指针L=i+1,右指针R=len-1,L 代码: 时间复杂度:O(N^2)
// @lc code=start
class Solution {
public List> threeSum(int[] nums) {
List
> lists = new ArrayList<>();
int len = nums.length;
if (len < 3 || nums == null) {
return lists;
}
Arrays.sort(nums);
for (int i = 0; i < len; ++i) {
if(nums[i]>0){
return lists;
}
if(i>0&&nums[i]==nums[i-1]){
continue;
}
int curr =nums[i];
int L=i+1;
int R=len-1;
while(L
空间复杂度:O(1)



