Find number -1 in sorted array

Likou Address

Binary search:

Quickly find the target value through binary search, and then spread the index of the target value to both sides of the target value

class Solution {
public:
    int search(vector<int>& nums, int target) {
        if (!nums.size()) return 0;

        int low = 0;
        int high = nums.size() - 1;
        int pivot;
        while (low <= high) {
            pivot = low + ((high - low) >> 1);
            if (nums[pivot] == target) {
                break;
            }
            else if (target < nums[pivot]) {
                high = pivot - 1;
            }
            else {
                low = pivot +1;
            }
        }
        if (low >high) return 0;

        low = pivot - 1;
        high = pivot + 1;
        while (0 <= low && nums[low] == target) --low;
        while (high <= nums.size() - 1 && nums[high] == target) ++high;

        return high - low - 1;
    }
};

 

 

Guess you like

Origin blog.csdn.net/TESE_yan/article/details/114440092
Recommended