704. Binary Search

AC Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int l = 0, r = nums.size();
        while(r - l > 1) {
            int mid = (l + r) / 2;
            
            if(nums[mid] < target)
                l = mid;
            else if(nums[mid] > target)
                r = mid;
            else
                return mid;
        }
        
        return nums[l] == target ? l : -1; // Oops
    }
};