1,题目要求
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.
二分搜索算法的实现。
2,题目思路
常规的算法实现。需要注意的是,在更新low和high时,low = mid + 1, high = mid - 1。
3,程序源码
static int pr = []() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
int search(vector<int>& nums, int target) {
int low = 0, high = nums.size()-1;
while(low <= high)
{
int mid = (low + high)/2;
if(nums[mid] == target) return mid;
else if(nums[mid]>target) high = mid-1;
else low = mid+1;
}
return -1;
}
};