leetcode 35. Search Insert Position
参考这里https://leetcode.wang/leetCode-35-Search-Insert-Position.html, 需要想到最简单的处理情况,如果数组只剩下 2 5,target 是 1, 3, 6 的时候,此时我们应该返回什么就行。
var searchInsert = function(nums, target) {
var left = 0, right = nums.length - 1;
while (left <= right) {
var mid = left + ((right - left) >> 1);
if (nums[mid] == target) {
return mid
} if (nums[mid] < target) {//[1,2,3,4,5,6,7], mid = 4, target = 5
left = mid + 1//left只能往mid靠
} else {
right = mid - 1//right只能往mid靠
}
}
return left
};
或者
var searchInsert = function(nums, target) {
var left = 0, right = nums.length - 1;
while (left <= right) {
var mid = left + ((right - left) >> 1);
if (nums[mid] == target) {
return mid
} else if (nums[mid] > target) {
right = mid - 1
} else {
left = mid + 1
}
}
return left
};
机器瞎学/数据掩埋/模式混淆/人工智障/深度遗忘/神经掉线/计算机幻觉/专注单身二十五年