题目描述:https://leetcode-cn.com/problems/search-insert-position/description/
思路:
- 假设所给数组是
[a1,a2,...,an]
,在左右两边加入无穷大和负无穷大,[-inf,a1,a2,...,an,inf]
- 在数组中寻找
ai < target <=ai+1
,返回i
按照这种思路,编写代码:
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
length = len(nums)
nums = [-float('inf')] + nums + [float('inf')]
for i in range(0,length+1):
if nums[i] < target <= nums[i+1] or i == length:
break
return i
这样写,有些复杂,参考别人的代码,可以简化为:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
i = 0
while i<len(nums) and nums[i]<target:
i = i + 1
return i
还可以通过二分法,降低运算速度:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
low = 0
high = len(nums)
while low < high:
mid = low + (high - low)/2
if nums[mid] > target:
high = mid
elif nums[mid] < target:
low = mid +1
else:
return mid
return low