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_left
class Solution(object):
def searchInsert(self, nums, target):
return bisect_left(nums, target)