- 首页 > it技术 > >
【leetcode】|leetcode 35. Search Insert Position 搜索插入位置 python 简单而高效的方法、二分查找
【LeetCode】编程心得&刷题总结
所有Leetcode题目不定期汇总在 Github, 欢迎大家批评指正,讨论交流。
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# Approach #1
# if target in nums:
#return nums.index(target)
# else:
#for index,num in enumerate(nums):
#if target < nums[0]:
#return 0
#if target > nums[-1]:
#return len(nums)
#if num < target and nums[index+1] > target:
#return index+1# Approach #2
# left , right = 0 , len(nums) - 1
# if target < nums[left]:
#return 0
# if target > nums[right]:
#return len(nums)
# if target in nums:
#return nums.index(target)
# while right - 1 > left :
#mid = ( left + right ) // 2
#iftarget < nums[mid]:
#right = mid
#elif nums[mid] < target:
#left = mid
#if nums[mid] == target:
#return mid
# return left + 1# Approach #3简化方法二
i, j = 0, len(nums) - 1
while i < j:
mid = (j - i) // 2 + i
if nums[mid] < target:
i = mid + 1
else:
j = mid - 1
return i+1 if nums[i] < target else i# 最后要写nums[i]而不是nums[0],因为需要处理二分查找失败的输入。
所有Leetcode题目不定期汇总在 Github, 欢迎大家批评指正,讨论交流。
推荐阅读