- 搜索插入位置
https://leetcode-cn.com/problems/search-insert-position/
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。 看到是排序的数组 那么就可以想到是二分法了。
先写一个我最先想到的办法 时间空间是O(N)
var searchInsert = function(nums, target) {
for(let i = 0;i<nums.length;i++) {
if(nums[i] >= target) return i
}
return nums.length
};
var searchInsert = function (nums, target) {
let left = 0
let right = nums.length
while (left <= right) {
let mid = Math.floor(left + (right - left) / 2)
if (nums[mid] === target) return mid
if (nums[mid] < target) {
left = mid + 1
} else {
right = mid - 1
}
}
return left
};
JAVA:
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while(left <= right) {
int mid = left + (right - left) >> 1;
if (target == nums[mid]) return midl
else if (target < nums[mid]) {
right = mid -1;
} else {
left = mid + 1
}
}
return left;
}
GO:
func searchInsert(nums []int, target int) int {
n := len(nums)
left, right := 0, n - 1
ans := n
for left <= right {
mid := (right - left) >> 1 + left
if target <= nums[mid] {
ans = mid
right = mid - 1
} else {
left = mid + 1
}
}
return ans
}