给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
示例 1:输入: nums = [1,3,5,6], target = 5
输出: 2
示例 2:输入: nums = [1,3,5,6], target = 2
输出: 1
示例 3:输入: nums = [1,3,5,6], target = 7
输出: 4来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/search-insert-position
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
个人版本(从头比较
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums: # 数组中找到目标值,并返回其索引
return nums.index(target)
else:
for i in range(len(nums)):
if nums[i] > target: # 比较目标与每个元素,元素如果比目标大,则目标该插入该元素位置
return i
if i == len(nums)-1: # 如果元素已经是最后一个(所有元素都比目标值小),则目标该插入列表最后
return i + 1
nums = [1, 3, 4, 6]
target = 7
print(Solution().searchInsert(nums, target))
看过示例后,上面版本缺少空列表情况判定(下面改进)
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if nums == []:
return 0
elif target in nums:
return nums.index(target)
else:
for i in range(len(nums)):
if nums[i] > target:
return i
if i == len(nums)-1:
return i + 1
nums = [1, 3, 4, 6]
target = 7
print(Solution().searchInsert(nums, target))
LeetCode示例代码(二分查找)
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
二分查找
"""
l, r = 0, len(nums) - 1
while l < r:
mid_idx = (l + r) // 2
mid = nums[mid_idx]
if mid == target:
return mid_idx
elif mid < target:
l = mid_idx + 1
else:
r = mid_idx - 1
print(l, r)
if l == r:
if nums[l] == target:
return l
elif nums[l] < target:
return l + 1
else:
return l
else: # l > r
return l