标签:bsp insert image info div class inf nbsp ima
思路:折半查找,关键在于停止循环的条件。
1 class Solution(object): 2 def searchInsert(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: int 7 """ 8 if target < nums[0]: 9 return 0 10 elif target > nums[len(nums) - 1]: 11 return len(nums) 12 13 i, j = 0, len(nums) - 1 14 while i < j-1: 15 if target == nums[i]: 16 return i 17 elif target == nums[j]: 18 return j 19 # 折半查找 20 temp = int((i + j) / 2) 21 if target == nums[temp]: 22 return temp 23 elif target > nums[temp]: 24 i = temp 25 elif target < nums[temp]: 26 j = temp 27 if target == nums[i]: 28 return i 29 else: 30 return i + 1 31 32 33 if __name__ == ‘__main__‘: 34 solution = Solution() 35 print(solution.searchInsert([1], 1))
标签:bsp insert image info div class inf nbsp ima
原文地址:https://www.cnblogs.com/panweiwei/p/12723085.html