题目链接:https://leetcode-cn.com/problems/3sum/
题目:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:
答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
返回:[[-1, 0, 1],[-1, -1, 2]]
该题目的难点是如何保证不重复,因为题目中要求“不可以包含重复的三元组”
如:原始数组 nums = [1, 0, 1, 2, -1, -4] 中,依次穷举结果会出现 [1,0,-1] 和 [0,1,-1]的结果集,这显然不合理
所以在解题之前将原始数组进行排序操作,这样在遍历的途中 如果 nums[i-1] = nums[i] 时,跳过即可。
所以、二话没说,和原来题目一样,上来一顿暴力解答,执行并提交。不过这次玩出事了。
如下是问题代码
// 暴力求解代码 ,验证没通过
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> lists = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < nums.length; j++) {
if (j > i+1 && nums[j] == nums[j - 1]) continue;
for (int k = j + 1; k < nums.length; k++)