class Solution(object): def searchInsert(self, nums, target): if target <= nums[0]: return 0 if target > nums[-1]: return len(nums) if target == nums[-1]: return len(nums)-1 for i in range(len(nums)-1): if nums[i] == target: return i # print(nums[i] < target) # print(nums[i+1] > target) if nums[i] < target and nums[i+1] > target: print (i) return i+1复制代码
上面的方式有点复杂,下面将代码简化一下:
class Solution(object): def searchInsert(self, nums, target): for i in range(len(nums)): if target <= nums[i]: return i return len(nums)复制代码
Python作为高级语言,当然有封装好的方法,而却不止一种:
class Solution(object): def searchInsert(self, nums, target): nums.append(target) nums.sort() return nums.index(target)复制代码
还可以使用第三方的库:
from bisect import bisect_leftclass Solution(object): def searchInsert(self, nums, target): return bisect_left(nums, target)复制代码