题目: 在一个排好序的数组中,插入目标值应该在的位置,不破坏当前的排列顺序
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
};
- 解法二
思路:目标值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
};