LeetCode 34. 在排序数组中查找元素的第一个和最后一个位置 Find First and Last Position of Element in Sorted Array

LeetCode 34. 在排序数组中查找元素的第一个和最后一个位置 Find First and Last Position of Element in Sorted Array

 

 

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> targetRange = {-1, -1};

        int leftIdx = extremeInsertionIndex(nums, target, true);

        if (leftIdx == nums.size() || nums[leftIdx] != target)
            return targetRange;
        
        targetRange[0] = leftIdx;
        targetRange[1] = extremeInsertionIndex(nums, target, false) - 1;

        return targetRange;
    }

    int extremeInsertionIndex(vector<int> nums, int target, bool left)
    {
        int lo = 0;
        int hi = nums.size();

        while (lo < hi)
        {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] > target || (left && target == nums[mid]))
                hi = mid;
            else
                lo = mid + 1;
        }
        return lo;
    }
};

 

上一篇:oracle 去掉锁表


下一篇:Java排序遇到的坑(转)