美文网首页
Search for a Range

Search for a Range

作者: CarlBlack | 来源:发表于2016-01-11 22:24 被阅读0次

    标签: 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;
        }
    };
    
    

    相关文章

      网友评论

          本文标题:Search for a Range

          本文链接:https://www.haomeiwen.com/subject/jfzqkttx.html