前言
  這題用的技巧是二分搜尋法,原理是每次循環都會將搜索範圍縮小一半。演算法通常需要使用二分思想,即每次能夠排除一半的範圍,快速的找出陣列中所要求的元素位置,這樣時間複雜度可達 O(log n),這裡有 JAVA 和 Python 的寫法。
題目
Given an array of integers
numswhich is sorted in ascending order, and an integertarget, write a function to searchtargetinnums. Iftargetexists, then return its index. Otherwise, return-1.
You must write an algorithm withO(log n)runtime complexity.
給定一個整數陣列
nums,這是個上升排序陣列,和一個目標整數target,寫一個方法去搜尋在nums陣列裡的目標整數target。如果目標整數target存在就回傳這個索引。否則回傳-1。
你必須寫一個時間複雜度是O(log n)的演算法。
題目連結:https://leetcode.com/problems/binary-search/
題目限制
1 <= numRows <= 301 <= nums.length <= 104104 < nums[i], target < 104
All the integers in nums are unique.nums is sorted in ascending order.
範例
1  | Input: nums = [-1,0,3,5,9,12], target = 9  | 
1  | Input: nums = [-1,0,3,5,9,12], target = 2  | 
思路&筆記
這題用的技巧是二分搜尋法,原理是每次循環都會將搜索範圍縮小一半。
- middle = start + ( end - start ) / 2 可取得中間值
 - 找出目標值在中間值的左側還是右側
 - 搜索範圍越來越小,直到最後回傳中間值就是答案
 
[注意點] 之所以要用上述中間值的寫法會比較安全,因如果 start 和 end 趨近於最大數時,兩者相加起來的合可能會造成整數溢位
JAVA 實現
1  | class Solution {  | 
Python 實現
使用了和 Java 一樣的邏輯執行,換成 Python 的寫法。
1  | class Solution:  | 
成績
| Language | Runtime | Memory | 
|---|---|---|
| Java | 0ms | 45.1MB | 
| Python | 251ms | 17.9MB |