搜索插入位置
题目链接:https://leetcode-cn.com/problems/search-insert-position/
题目:给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置
二分法(python)
# 时间:24ms
# 空间:13.5MB
def search(nums, target):
lift = 0
right = len(nums) - 1
while lift <= right:
mid = int((lift + right)/2)
if nums[mid] == target:
return mid
elif nums[mid] < target:
lift = mid + 1
else:
right = mid-1
return right + 1
print(search([1,3,4,5,6,7,9,14,23],2))
二分法(java)
//时间:0ms
//空间:38.4MB
class Solution {
public int searchInsert(int[] nums, int target) {
int left=0, right=nums.length-1;
int mid=0;
while(left<=right) {
mid=(right+left)/2;
if(nums[mid]==target) {
return mid;
}
if(nums[mid]>target) {
right=mid-1;
} else {
left=mid+1;
}
}
return left;
}
}