zoukankan      html  css  js  c++  java
  • 数组

     
    给定一个整数数组 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
  • 相关阅读:
    迁移学习
    GAN
    PCA
    LSTM
    hdu 1754 I Hate It 线段树
    hdu 4292 Food 最大流
    hdu 2222 Keywords Search AC自动机
    hdu 3572 Task Schedule hdu 2883 kebab 最大流
    poj 1966 Cable TV Network 点连通度
    hdu 2236 匹配
  • 原文地址:https://www.cnblogs.com/xiaoliziaaa/p/13336298.html
Copyright © 2011-2022 走看看