Skip to content

Latest commit

 

History

History
63 lines (54 loc) · 1.15 KB

1.md

File metadata and controls

63 lines (54 loc) · 1.15 KB

1. Two Sum

https://leetcode.com/problems/two-sum/

随便写了一个O(n2)的解决方案,效率明显比较低。

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
  for (var i = 0; i < nums.length - 1; i++) {
    for (var j = i + 1; j < nums.length; j++) {
      if (nums[i] + nums[j] === target) {
        return [i, j];
      }
    }
  }
};
16 / 16 test cases passed.
Status: Accepted
Runtime: 292 ms

接下来用Map实现,时间复杂度为O(n)

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
  var map = new Map();
  var numberToFind;
  var result = [];

  for (i = 0; i < nums.length; i++) {
    numberToFind = target - nums[i];

    // 如果map中包含numberToFind,跳出循环
    if (map.has(numberToFind)) {
      result.push(map.get(numberToFind));
      result.push(i);
      break;
    }

    // 如果map中不包含numberToFind,将当前数据放入map
    map.set(nums[i], i);
  }

  return result;
};
16 / 16 test cases passed.
Status: Accepted
Runtime: 148 ms