LeetCode_Search Insert Position

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.
(在有序数组中检索)

Example:



1. 二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
n = len(nums)
if n == 0:
return 0

left, right = 0, n-1

while left <= right:
middle = (left + right) // 2

if target == nums[middle]:
return middle
elif target < nums[middle]:
right = middle - 1
else:
left = middle + 1

return left