LeetCode 704 Binary Search 模板
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.
Solution
点击查看代码
class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
if(n==1){
if(nums[0]==target)return 0;
else return -1;
}
int l=0,r=n-1;
int mid;
while(l<r){
mid = (l+r)>>1;
if(nums[mid]<target)l=mid+1;
else if(nums[mid]==target)return mid;
else r=mid;
}
if(nums[r]!=target)return -1;
else return r;
}
};