Leetcode15-三数之和
Leetcode15-三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。注意:答案中不可以包含重复的三元组。
这道题最麻烦的地方在于必须确保最后的结果中没有重复的三元组。另外,同一个位置的数字不能被使用多次,但不同位置的相同数字可以放到同一个三元组中。我的思路是先对数组排序,然后通过一个map保存每个数字出现的次数,最后枚举所有和为0且满足出现次数条件的三元组。(以我的智力水平只能想出这种解法了)
1 var threeSum = function(nums) { 2 let res = []; 3 if (nums.length <= 2) { 4 return res; 5 } 6 7 nums.sort( 8 (a,b) => { 9 return a - b; 10 } 11 ) 12 13 numToTimes = new Map(); 14 for (let num of nums) { 15 if (numToTimes.has(num)) { 16 numToTimes.set(num, numToTimes.get(num) + 1); 17 } else { 18 numToTimes.set(num, 1); 19 } 20 } 21 22 let uniqueNums = []; 23 numToTimes.forEach( 24 (v, k) => { 25 uniqueNums.push(k); 26 } 27 ) 28 29 for (let i = 0; i < uniqueNums.length; i++) { 30 if (3 * uniqueNums[i] === 0 && numToTimes.get(uniqueNums[i]) >= 3) { 31 res.push([uniqueNums[i],uniqueNums[i],uniqueNums[i]]); 32 } 33 for(let j = i + 1; j < uniqueNums.length; j++) { 34 if (2 * uniqueNums[i] + uniqueNums[j] === 0 && numToTimes.get(uniqueNums[i]) >= 2) { 35 res.push([uniqueNums[i], uniqueNums[i], uniqueNums[j]]); 36 } 37 38 if (2 * uniqueNums[j] + uniqueNums[i] === 0 && numToTimes.get(uniqueNums[j]) >= 2) { 39 res.push([uniqueNums[j], uniqueNums[j], uniqueNums[i]]); 40 } 41 42 c = 0 - uniqueNums[i] - uniqueNums[j]; 43 if (numToTimes.get(c) >= 1 && c > uniqueNums[j]) { 44 res.push([c, uniqueNums[i], uniqueNums[j]]); 45 } 46 47 } 48 } 49 return res; 50 }; 51 52 nums = [-1,0,1,2,-1,-4]; 53 res = threeSum(nums); 54 console.log(res); //[[-1,-1,2],[1,-1,0]

浙公网安备 33010602011771号