美文网首页leetcode --- js版本
leetcode-Easy-第9期-数组- Search Ins

leetcode-Easy-第9期-数组- Search Ins

作者: 石头说钱 | 来源:发表于2019-03-02 14:12 被阅读0次

题目: 在一个排好序的数组中,插入目标值应该在的位置,不破坏当前的排列顺序

  • Example1
Input: [1,3,5,6], 5
Output: 2
Example 2:
  • Example1
Input: [1,3,5,6], 2
Output: 1
  • Example 3:
Input: [1,3,5,6], 7
Output: 4
  • Example 4:
Input: [1,3,5,6], 0
Output: 0
  • 解法一
var searchInsert = function(nums, target) {
 const len = nums.length;
 let res = null
 if(nums[0] > target) return 0
 if(nums[len - 1] <target) return len
 
  for(let idx = 0; idx < len;idx++){
     const next = idx + 1
     if(nums[idx] === target) {res = idx}
     if(nums[idx] < target && target < nums[next]) {res = idx + 1} 

 }
  return res
  
};

  • 解法二
    思路:目标值target的左边的值肯定比他小,遍历数组每发现一个数值比target小,就将index+1,直到数组中的值不再比target小,就可以确定最后要出入的位置为index+1
var searchInsert = function(nums, target) {
  const len = nums.length
  let index = 0
  for(let i=0;i<len;++i){
    if(nums[i] === target) return i
    if(nums[i] < target) index++
  }
  return index
};

相关文章

网友评论

    本文标题:leetcode-Easy-第9期-数组- Search Ins

    本文链接:https://www.haomeiwen.com/subject/seveuqtx.html