leetcode 35. 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.
思路:
這道題基本沒有什么難度,實在不理解為啥還是Medium難度的,完完全全的應(yīng)該是Easy啊,三行代碼搞定的題,只需要遍歷一遍原數(shù)組,若當前數(shù)字大于或等于目標值,則返回當前坐標,如果遍歷結(jié)束了,說明目標值比數(shù)組中任何一個數(shù)都要大,則返回數(shù)組長度n即可
思路二:二分法
var searchInsert = function(nums, target) {
var l=0;
var r=nums.length;
while(l<r){
var m= Math.floor((l+r)/2);
if(nums[m]>target){
r=m;
}else if (nums[m]<target){
l=m+1;
}else{
r=m;
}
}
return r;
};