leetcode-Easy-第9期-数组- Search Insert Position

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

  • 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
};
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容