leetcode34. 在排序数组中查找元素的第一个和最后一个位

2019-09-26  本文已影响0人  今天不想掉头发

二分查找不用说,主要是这里注意如何找到数组中等于target的最左边和最右边的索引位置


image.png
class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> res = {-1, -1};
        int rightIndex = findRightIndex(nums, target);
        if (rightIndex < 0 || nums[rightIndex] != target) return res;
        int leftIndex = findLeftIndex(nums, target);
        res[0] = leftIndex;
        res[1] = rightIndex;
        return res;
    }
    
    int findLeftIndex(vector<int>& nums, int target) {
        int lo = 0, hi = nums.size() - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] < target) lo = mid + 1;
            else hi = mid - 1;
        }
        return lo;
    }
    
    int findRightIndex(vector<int>& nums, int target) {
          int lo = 0, hi = nums.size() - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] > target) hi = mid - 1;
            else lo = mid + 1;
        }
        return hi;
    }
};
上一篇下一篇

猜你喜欢

热点阅读