leetcode --- js版本

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

2019-03-02  本文已影响0人  石头说钱

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

Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Input: [1,3,5,6], 7
Output: 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
  
};

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
};
上一篇下一篇

猜你喜欢

热点阅读