Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var searchInsert = function(nums, target) {
if(nums.indexOf(target) != -1){
return nums.indexOf(target);
}else{
nums.push(target);
nums = nums.sort(function(a,b){return a-b;});
return nums.indexOf(target);
}
};

本文介绍了一个算法,用于在已排序的数组中查找给定数字的索引,如果不存在则计算其应有的位置。通过简单的遍历和排序,实现目标值的定位。
92

被折叠的 条评论
为什么被折叠?



