题意:给定一个数组返回target的下标,如果没有返回 - 1
https://leetcode.com/problems/binary-search/description/
思路:数组有序,方便我们构造XXXOOO的形式,套用二分模版,先算出l和r,然后想想是不是一定有答案这道题中答案是nums[l] == target, 如果没有答案就是-1.
class Solution {
public:int search(vector<int>& nums, int target) {int l = 0;int r = nums.size() - 1;while (l < r) {int mid = l + (r - l) / 2;if (nums[mid] >= target) {r = mid;} else {l = mid + 1;}}if (nums[l] == target) {return l;} else {return -1;}}
};
算法复杂度:O(logN) N是数组长度 空间O(1)