解题思路
排序 + 双指针
Java代码
class Solution {
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList();
int len = nums.length;
if(nums == null || len < 3) return ans;
Arrays.sort(nums); // 排序
for (int i = 0; i < len ; i++) {
if(nums[i] > 0) break; // 如果当前数字大于0,则三数之和一定大于0,所以结束循环
if(i > 0 && nums[i] == nums[i-1]) continue; // 去重
int L = i+1;
int R = len-1;
while(L < R){
int sum = nums[i] + nums[L] + nums[R];
if(sum == 0){
ans.add(Arrays.asList(nums[i],nums[L],nums[R]));
L++;
R--;
while (L<R && nums[L] == nums[L-1]) L++; // 去重
while (L<R && nums[R] == nums[R+1]) R--; // 去重
}
else if (sum < 0) L++;
else if (sum > 0) R--;
}
}
return ans;
}
}
python 代码
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
n=len(nums)
res=[]
# 数组为空,或者长度小于2
if(not nums or n<3):
return []
# 数组长度大于3
for i in range(n):
if(nums[i]>0):
break
if(i>0 and nums[i]==nums[i-1]):
continue
L=i+1
R=n-1
while(L<R):
if(nums[i]+nums[L]+nums[R]==0):
res.append([nums[i],nums[L],nums[R]])
L=L+1
R=R-1
# 去除重复情况
while(L<R and nums[L]==nums[L-1]):
L=L+1
# 去除重复情况
while(L<R and nums[R]==nums[R+1]):
R=R-1
elif(nums[i]+nums[L]+nums[R]>0):
R=R-1
else:
L=L+1
return res
if __name__ == '__main__':
###################
s = Solution()
# res = s.threeSum([-1, 0, 1, 2, -1, -4])
# res = s.threeSum([0,0,0])
# res = s.threeSum([1, 2, -2, -1])
res = s.threeSum([-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6])
print(res)