题解 | #二分查找-I#
二分查找-I
http://www.nowcoder.com/practice/d3df40bd23594118b57554129cadf47b
简单二分
C++代码:
class Solution {
public:
int search(vector<int>& nums, int target) {
if (nums.empty()) return -1;
int l = 0, r = nums.size() - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > target) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return -1;
}
};