我的個人微信公衆號:Microstrong
微信公衆號ID:MicrostrongAI
微信公衆號介紹:Microstrong(小強)同學主要研究機器學習、深度學習、計算機視覺、智能對話系統相關內容,分享在學習過程中的讀書筆記!期待您的關注,歡迎一起學習交流進步!
知乎主頁:https://www.zhihu.com/people/MicrostrongAI/activities
704. Binary Search
Given a sorted (in ascending order) integer array nums
of n
elements and a target
value, write a function to search target
in nums
. If target
exists, then return its index, otherwise return -1
.
Example 1:
Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 exists in nums and its index is 4
Example 2:
Input:nums = [-1,0,3,5,9,12], target = 2 Output: -1 Explanation: 2 does not exist in nums so return -1
Note:
- You may assume that all elements in
nums
are unique. n
will be in the range[1, 10000]
.- The value of each element in
nums
will be in the range[-9999, 9999]
.
解題思路:
(1)二分查找
class Solution:
def search(self, nums: List[int], target: int) -> int:
if nums is None or len(nums) == 0:
return -1
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1