## 704. Binary Search 之前面試有考刷題,所以有刷過一陣子題目(~~不過都是Easy就是了~~),所以想紀錄之前紀錄一些基礎題。 >Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. ``` You must write an algorithm with O(log n) runtime complexity. 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 ``` ### 需要已排序陣列中,尋找到 target 數字 #### 思路 * 將數列從中間劃分為兩半,根據目標值與中間值的比較來決定搜尋哪一半。 這個過程會反覆縮小搜尋範圍,直到找到目標或搜尋範圍為空。 時間複雜度:`O(log n)`,因為每次都將搜尋範圍減半。 > 其實簡單來說就是小時候玩的終極密碼 ### Code ```javascript= function search(nums, target) { let low = 0; let high = nums.length - 1; while (low <= high) { let mid = Math.floor((low + high) / 2); if (nums[mid] === target) { return mid; } if (nums[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return -1; } const nums1 = [-1, 0, 3, 5, 9, 12]; const target1 = 9; console.log(search(nums1, target1)); // 4 ```