原题是这样的:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
这个去重是真的让人一个头两个大,听了网上大佬讲解才恍然大悟,今天七夕,学了一点点,在这里记录一下吧。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
/*三个指针,三去重,本题的重头戏!*/
var threeSum = function (nums) {
let result = [] /*用来存储结果*/
nums.sort(function (a, b) { return a > b ? 1 : -1 })
/*排序 从小到大,三数相加和大于0,最大的数字缩小,指针end往前移动三数之和小于零,中间的动态变化的数字增大,指针start往后,i用来遍历*/
for (let i = 0; i < nums.length - 2; i++) {
/*nums.length - 2减去2是因为有start和end两个指针,start不能和end重叠*/
if (i === 0 || nums[i] !== nums[i - 1]) {
/*第一次去重 [-1,0,1,2,-1,2] [-1,0,1]是一个答案,不能因为有两个-1就返回两个答案,排序之后,重复的元素肯定相邻,所以满足nums[i] !== nums[i - 1],就是去除了重复答案
//while (i === 0 || nums[i] !== nums[i - 1])可不能写成while,不然会一直循环在i=0处*/
let start = i + 1, end = nums.length - 1
while (start < end) {/*因为指针start和end是要动的,所以是while*/
if (nums[i] + nums[start] + nums[end] === 0) {
result.push([nums[i], nums[start], nums[end]])
start++
end--
while (start < end && nums[start] === nums[start - 1]) { start++ }/*第二次去重,道理和第一次去重一样,避免start指针指向的那个位置的元素重复*/
while (start < end && nums[end] === nums[end + 1]) { end-- }
/*第三次去重,道理和第一次去重一样,避免end指针指向的那个位置的元素重复*/
} else if (nums[i] + nums[start] + nums[end] > 0) {
end--
} else {
start++
}
}
}
}
return result
};
</script>
</body>
</html>
总结:
1、排序,让相同的元素相邻,方便第一次去重
2、if和while不能随便用,while还要循环,而if只判断一次
3、start永远要小于end,end要满足小于数组长度减2,防止越界
4、三个位置都需要去重