var threeSum = function(nums) { var ans = []; var nums = nums.sort(function(a,b){return a - b}); var flag = 0; while(flag < nums.length - 2){ if (nums[flag] > 0){ break; } var l = flag + 1,r= nums.length - 1; while(l < r){ var res = nums[flag] + nums[l] + nums[r]; if(res === 0){ ans.push(new Array(nums[flag], nums[l], nums[r])); while(++l < r && nums[l - 1] === nums[l]){} while(l < --r && nums[r + 1] === nums[r]){} }else if(res < 0){ while(++l < r && nums[l - 1] === nums[l]){} }else{ while(l < --r && nums[r + 1] === nums[r]){} } } while(++flag < nums.length - 2 && nums[flag] === nums[flag - 1]){} } return ans; };
关键中的关键是排序后最左侧为正数的优化 节约大量运行时间
原文地址:https://www.cnblogs.com/qq965921539/p/12241762.html
时间: 2024-10-07 14:19:50