LeetCode - 3Sum

2019-04-12  本文已影响0人  yingjieg
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function(nums) {
  if (nums.length < 3) {
    return [];
  }

  const sortedNums = nums.sort((a, b) => a - b);
  const length = nums.length;
  const data = [];

  for (let i = 0; i < length - 2; i++) {
    if (sortedNums[i] > 0) break;
    if (i > 0 && sortedNums[i] === sortedNums[i - 1]) {
      continue;
    }

    let l = i + 1;
    let r = length - 1;
    const target = sortedNums[i];
    while (l < r) {
      if (sortedNums[l] + sortedNums[r] + target === 0) {
        data.push([target, sortedNums[l], sortedNums[r]]);

        while (l < r && sortedNums[l] === sortedNums[l + 1]) l++; // ignore duplicate left values
        while (l < r && sortedNums[r] === sortedNums[r - 1]) r--; // ignore duplicate right values
        l++;
        r--;
      } else if (sortedNums[l] + sortedNums[r] + target < 0) { // find next large values.
        l++;
      } else { // find next small values.
        r--;
      }
    }
  }

  return data;
};

Success

Details

Runtime: 164 ms, faster than 99.23% of JavaScript online submissions for 3Sum.

Memory Usage: 47 MB, less than 42.73% of JavaScript online submissions for 3Sum.

上一篇下一篇

猜你喜欢

热点阅读