Search for a Range

标签: C++ 算法 LeetCode 数组 二分查找

每日算法——leetcode系列


问题 Search for a Range

Difficulty: Medium

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

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

翻译

搜索(目标的)所在范围

难度系数:中等

给定一个有序整数数组,找出给定值在其中的起始与结束索引。

算法的时间复杂度必须为O(logn)。

如果数组中没有指定值,返回[-1, -1]。

例如,给定[5, 7, 7, 8, 8, 10],目标值为8,返回[3, 4]。

思路

对于有序数组, 查找可以用二分查找
由于有重复的值,如果二分法找到目标,则分两部分继续二分查找
如果没找到,返回[-1, -1]

代码

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int n = (int)nums.size();
        int pos = binarySearch(nums, 0, n-1, target);

        vector<int> result;
        int low = -1, high = -1;
        if (pos >= 0){
            low = pos;
            int l = low;
            while (l >= 0) {
                low = l;
                l = binarySearch(nums, 0, low - 1, target);
            }
            
            high = pos;
            int h = high;
            while (h >= 0){
                high = h;
                h = binarySearch(nums, high + 1, n-1, target);
            }
        }
        
        result.push_back(low);
        result.push_back(high);
        return result;

    }
    
private:
    int binarySearch(vector<int> nums, int low, int high, int target){
        
        while (low <= high) {
            int mid = low + (high - low)/2;
            if (nums[mid] == target) {
                return mid;
            }
            if (target > nums[mid]) {
                low = mid + 1;
            }
            if (target < nums[mid]) {
                high = mid - 1;
            }
        }
        return -1;
    }
};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目描述 Given an array of integers sorted in ascending order...
    BookThief阅读 406评论 0 0
  • 题目 给定一个可能包含重复数字已排过序的数组和一个目标值,在数组中找到目标值第一次出现和最后一次出现的位置,如果没...
    yxwithu阅读 134评论 0 0
  • Given an array of integers sorted in ascending order, fin...
    matrxyz阅读 199评论 0 0
  • 题目 Given an array of integers sorted in ascending order, ...
    时光杂货店阅读 145评论 0 0
  • 文/高昂 屋子是南北长,我的床在最北头,窗户在最南头,不知道外面是月光还是灯光,能从最南头照到屋里最北边的墙上,和...
    公园阅读 158评论 0 0