leetcood学习笔记-35-二分法
题目:
第一次提交;
class Solution: def searchInsert(self, nums: List[int], target: int) -> int: for i in range(len(nums)): if nums[i] >= target : return i if i == (len(nums)-1) and nums[i]<target: return i+1
法二:
class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if target in nums: return nums.index(target) else: nums.append(target) nums.sort() return nums.index(target)
方法三;二分法
class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ low = 0 high = len(nums) while low < high: mid = low + (high - low)//2#Python 的//才是取整数商舍余,/不取整 会得到小数商(Python2中3//2 3/2都是取整,Python3中3//2是取整,3/2是浮点。) if nums[mid] > target: high = mid elif nums[mid] < target: low = mid +1 else: return mid return low