数组

 
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

*/ /** * @param {number[]} nums * @param {number} target * @return {number[]} */
let twoSum = (nums, target) => {
  let targetMap = new Map()
  let resArr = []
  nums.forEach((item, index) => {
    if (targetMap.has(target - item)) {
      resArr.push(targetMap.get(target - item))
      resArr.push(index)
      return
    }
    targetMap.set(item, index)

  })
  return resArr
}
 

 

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

https://leetcode-cn.com/problems/search-insert-position/

/**
 * 在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
 * @param {Array[]} nums 
 * @param {number} target 
 * @return {number} index 
 */

const searchInsert = function (nums, target) {
  let index = nums.findIndex(item => item === target)
  // 存在索引不为-1
  if (index !== -1) return index
  for (let i = 0; i < nums.length; i++) {
    if (target >= Math.max(...nums)) {
      nums.push(target)
      return nums.length - 1
    }
    else if (target <= Math.min(...nums)) {
      nums.unshift(target)
      return 0
    }
    else if (nums[i] <= target && target <= nums[i + 1]) {
      nums.splice(i + 1, 0, target)
      return i + 1
    }
  }

};
View Code

 

posted on 2020-07-18 16:44  章画  阅读(167)  评论(0编辑  收藏  举报

导航