JS解決查找表與求和問題

兩數之和

給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。你可以假設每種輸入只會對應一個答案。但是,你不能重複利用這個數組中同樣的元素。

示例:

給定 nums = [2, 7, 11, 15], target = 9

因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
  • 方法一:暴力解法

遍歷所有數據對,判斷是否等於 target,時間複雜度度 O(n^2)

//執行用時 :124 ms, 在所有 javascript 提交中擊敗了54.32%的用戶
//內存消耗 :35.2 MB, 在所有 javascript 提交中擊敗了21.37%的用戶
var twoSum = function (nums, target) {
  var res = [];
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[i] + nums[j] == target) {
        res.push(i, j);
        return res;
      }
    }
  }
};
  • 方法二:查找表
//dict
//執行用時 :52 ms, 在所有 javascript 提交中擊敗了99.77%的用戶
//內存消耗 :34.9 MB, 在所有 javascript 提交中擊敗了30.64%的用戶
var twoSum = function (nums, target) {
  let res = {};
  for (let i = 0; i < nums.length; i++) {
    if (res.hasOwnProperty(nums[i])) {
      return [res[nums[i]], i];  //找到i下標對應要找的值,則返回
    } else {
      res[target - nums[i]] = i; //保存對應i下標要找的值
    }
  }
};

//數組
//執行用時 :152 ms, 在所有 javascript 提交中擊敗了33.55%的用戶
//內存消耗 :34.3 MB, 在所有 javascript 提交中擊敗了84.79%的用戶
var twoSum = function (nums, target) {
  for (let i = 0; i < nums.length; i++) {
    let result = nums.lastIndexOf(target - nums[i]);
    if (result !== -1 && result !== i) {
      return [i, result]
    }
  }
};

三數之和

給定一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重複的三元組。注意:答案中不可以包含重複的三元組。

示例:

例如, 給定數組 nums = [-1, 0, 1, 2, -1, -4],

滿足要求的三元組集合爲:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
  • 雙指針
//執行用時 :196 ms, 在所有 javascript 提交中擊敗了68.70%的用戶
//內存消耗 :46.8 MB, 在所有 javascript 提交中擊敗了57.55%的用戶
var threeSum = function (nums) {
  if (!nums || nums.length < 3) return [];
  nums.sort((a, b) => { return a - b; });

  let res = [];
  for (let i = 0; i < nums.length - 2; i++) {
    let l = i + 1;
    let r = nums.length - 1;

    //去重
    if (i > 0 && nums[i] === nums[i - 1]) continue;

    while (l < r) {
      let sum = nums[i] + nums[l] + nums[r];
      if (sum < 0) {
        l++;
      } else if (sum > 0) {
        r--;
      } else {
        res.push([nums[i], nums[l], nums[r]]);
        while (nums[l] === nums[l + 1]) l++;
        while (nums[r] === nums[r - 1]) r--;
        l++;
        r--;
      }
    }
  }
  return res;
};
  • 暴力解法超時:311 / 313 個通過測試用例
var threeSum = function (nums) {
  if (nums.length < 3) {
    return [];
  }
  let res = [];
  let key = {};
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      let index = nums.indexOf(-(nums[i] + nums[j]), j + 1);
      if (index != -1) {
        let temp = [nums[i], nums[j], nums[index]].sort((a, b) => { return a - b })
        let str = temp.join('');
        if (!key.hasOwnProperty(str)) {
          key[str] = 1;
          res.push(temp);
        }
      }
    }
  }
  return res;
};

四數之和

給定一個包含 n 個整數的數組 nums 和一個目標值 target,判斷 nums 中是否存在四個元素 a,b,c 和 d ,使得 a + b + c + d 的值與 target 相等?找出所有滿足條件且不重複的四元組。注意:答案中不可以包含重複的四元組

示例:

給定數組 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

滿足要求的四元組集合爲:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]
  • 在三數之和的基礎上添加一層循環
//執行用時 :96 ms, 在所有 javascript 提交中擊敗了95.30%的用戶
//內存消耗 :37.1 MB, 在所有 javascript 提交中擊敗了42.64%的用戶
var fourSum = function (nums, target) {
  if (!nums || nums.length < 4) return [];
  nums.sort((a, b) => { return a - b; });

  let res = [];
  for (let i = 0; i < nums.length; i++) {
    let threeSum = target - nums[i];
    if (i > 0 && nums[i] == nums[i - 1]) { continue; }

    for (let j = i + 1; j < nums.length - 2; j++) {
      let l = j + 1;
      let r = nums.length - 1;

      if (j > i + 1 && nums[j] == nums[j - 1]) { continue; }
      while (l < r) {
        let sum = nums[j] + nums[l] + nums[r];
        if (sum < threeSum) {
          l++;
        } else if (sum > threeSum) {
          r--;
        } else {
          res.push([nums[i], nums[j], nums[l], nums[r]]);
          while (nums[l] === nums[l + 1]) l++;
          while (nums[r] === nums[r - 1]) r--;
          l++;
          r--;
        }
      }
    }
  }
  return res;
};

  • 雙指針+Set去重
//執行用時 :124 ms, 在所有 javascript 提交中擊敗了48.90%的用戶
//內存消耗 :38 MB, 在所有 javascript 提交中擊敗了24.81%的用戶

var fourSum = function (nums, target) {
  let set = new Set()
  nums.sort((a, b) => a - b)
  for (let i = 0; i < nums.length - 3; i++) {
    for (let j = i + 1; j < nums.length - 2; j++) {
      let start = j + 1, end = nums.length - 1
      while (start < end) {
        let sum = nums[i] + nums[j] + nums[start] + nums[end]
        if (sum < target) {
          start++
        } else if (sum > target) {
          end--
        } else {
          set.add([nums[i], nums[j], nums[start], nums[end]].join(','))
          start++
          end--
        }
      }
    }
  }
  return [...set].map(v => v.split(',').map(v => +v))
};
  • 固定中間兩個數然後不斷逼近
//執行用時 :124 ms, 在所有 javascript 提交中擊敗了48.90%的用戶
//內存消耗 :37.7 MB, 在所有 javascript 提交中擊敗了31.01%的用戶
var fourSum = function (nums, target) {
  if (nums.length < 4)
    return [];
  nums.sort((a, b) => a - b);
  var hash = new Map();
  for (var midF = 1; midF < nums.length - 2; midF++) {
    for (var mid = midF + 1; mid < nums.length - 1; mid++) {
      if (mid - 1 !== midF && nums[mid] === nums[mid - 1])
        continue;
      var start = 0,
        end = nums.length - 1;
      while (start < midF && end > mid) {
        if (nums[start] + nums[midF] + nums[mid] + nums[end] === target) {
          var arr = [nums[start], nums[midF], nums[mid], nums[end]],
            str = arr.join('-');
          if (hash.has(str) === false) {
            hash.set(str, arr);
          }
        }
        if (nums[start] + nums[midF] + nums[mid] + nums[end] > target)
          end -= 1;
        else
          start += 1;
      }
    }
  }
  return [...hash].map((a) => a[1]);
};

來源:力扣(LeetCode)https://leetcode-cn.com

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章