问题描述:
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
class Solution {
public:
int search(vector<int>& nums, int target) {
int nLeft = 0;
int nRight= nums.size() - 1;
int nMid = 0;
while (nLeft <= nRight)
{
nMid = nLeft + (nRight - nLeft) / 2;
if(nums[nMid] > target)
{
nRight = nMid -1;
}
else if (nums[nMid] < target)
{
nLeft = nMid + 1;
}
else{
return nMid;
}
}
return -1;
}
};