LeetCode数组2题——01 TwoSum 和 35 SearchInsertPosition

151 阅读1分钟

「这是我参与11月更文挑战的第25天,活动详情查看:2021最后一次更文挑战

1.TwoSum

题目

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Only one valid answer exists.

题目大意

给定数组nums及整数target,求nums中和为target的两个不同元素的索引

解题思路

遍历数组,将元素值作为key元素索引作为value保存在 Map 中。

对于元素nums[m],在 Map 中查找是否存在键为target - nums[m]的元素,若存在则找到索引对

代码

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function (nums, target) {
  const map = new Map();
  for (let i = 0; i < nums.length; i++) {
    const key = target - nums[i];
    if (map.has(key)) {
      return [i, map.get(key)];
    } else {
      map.set(nums[i], i);
    }
  }
};

复杂度

时间:O(n)

空间:O(n)

35.SearchInsertPosition

题目

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [1,3,5,6], target = 5
Output: 2

Example 2:

Input: nums = [1,3,5,6], target = 2
Output: 1

Example 3:

Input: nums = [1,3,5,6], target = 7
Output: 4

Example 4:

Input: nums = [1,3,5,6], target = 0
Output: 0

Example 5:

Input: nums = [1], target = 0
Output: 0

Constraints:

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums contains distinct values sorted in ascending order.
  • -10^4 <= target <= 10^4

题目大意

给定一个有序(从小到大)、无重复元素的数组nums和整数target,找出target在数组中的位置。

若数组中不存在target,求target的插入位置,使得插入后数组仍然保持有序

解题思路

二分查找:在一个有序数组中查找指定元素,我们第一时间都会想到二分查找

假设元素插入的位置是ins,则:nums[ins - 1] < target <= nums[ins]

所以我们要找的是第一个大于等于target的元素位置

代码

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var searchInsert = function (nums, target) {
  let left = 0;
  let right = nums.length - 1;
  let res = nums.length; // 如果target大于所有元素,那么插入位置就是nums.length
  while (left <= right) {
    // let mid = Math.floor((left + right) / 2);
    // 用位运算代替,效率更高
    let mid = (left + right) >> 1; 
    // 如果(left + right)有可能溢出,就用
    // let mid = ((right - left) >> 1) + left;
    if (target === nums[mid]) {
      return mid;
    }
    if (target < nums[mid]) {
      res = mid;
      right = mid - 1;
    } else {
      left = mid + 1;
    }
  }
  return res;
};

复杂度

时间:O(logn)

空间:O(1)