題目連結(https://leetcode.com/problems/binary-search/description/)
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.
今天分享搜尋的經典題目,可延伸至許多應用問題,也要注意其與 Binary Search Tree 的比較
nums
和要搜尋目標數字 target
。target
的 index,不存在則輸出 -1。Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4(9 的 index)
#線性搜尋
class Solution {
public:
int search(vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == target) {
return i; // 找到目標,返回索引
}
}
return -1; // 沒有找到目標,返回 -1
}
};
#二分搜尋
class Solution {
public:
int search(vector<int>& nums, int target) {
return bs(nums, 0, nums.size() - 1, target);
}
private:
int bs(vector<int>& nums, int l, int r, int target){
if(l > r)
return -1;
int m = l + (r-l)/2; //避免溢位
if(nums[m] == target)
return m;
else if(nums[m] < target) //遞迴搜尋右半
return bs(nums, m+1, r, target);
else //遞迴搜尋左半
return bs(nums, l, m-1, target);
}
};
m = 2, nums[2] = 3 < 9, return bs(nums, 3, 5, 9)
m = 4, nums[4] = 9 = target, return 4 (9 的 index)
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
中間值 m = left +(right-left)/2 避免溢位
ps. 部分內容經 AI 協助整理