704. 二分查找

  

 

通常可以写出的二分法:mid = (start + end) / 2;

另一种写法:mid = start + (end - start) / 2,可防止 (start + end) 溢出。

代码一:

 1 class Solution(object):
 2     def search(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: int
 7         """
 8         if target in nums:
 9             return nums.index(target)
10         else:
11             return -1

代码二:

 1 class Solution(object):
 2     def search(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: int
 7         """
 8         i, j = 0, len(nums)-1
 9 
10         while i <= j:
11             mid = int((i+j) / 2)
12             if nums[mid] == target:
13                 return mid
14             elif nums[mid] < target:
15                 i = mid+1
16             else:
17                 j = mid-1
18         return -1

代码三:

 1 class Solution(object):
 2     def search(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: int
 7         """
 8         i, j = 0, len(nums)-1
 9         if i == j and nums[i] == target:
10             return i
11         while i <= j:
12             mid = i + int((j - i) / 2)
13             if nums[mid] == target:
14                 return mid
15             elif nums[mid] < target:
16                 i = mid+1
17             else:
18                 j = mid-1
19         return -1

 

posted @ 2020-04-21 22:54  人间烟火地三鲜  阅读(180)  评论(0编辑  收藏  举报