1、渣渣渣法一:耗时226ms,beats 0.02%
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if nums == []:
return 0
n = len(nums)
if n ==1 :
if target <= nums[0]:
return 0
else:
return 1
for i in range(n-1):
if target in nums:
if nums[i] == target:
return i
if nums[-1] == target:
return n-1
else:
if nums[i] < target and nums[i+1]> target:
return i+1
if target < nums[0]:
return 0
if target > nums[-1]:
return n
2、二叉树
def searchInsert(self, nums, target):
l , r = 0, len(nums)-1
while l <= r:
mid=(l+r)/2
if nums[mid]== target:
return mid
if nums[mid] < target:
l = mid+1
else:
r = mid-1
return l
3、获取原数列中比target小的所有数
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
return len([x for x in nums if x<target])