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閱讀 404評論 0 0
  • 題目 給定一個可能包含重復數字已排過序的數組和一個目標值,在數組中找到目標值第一次出現和最后一次出現的位置,如果沒...
    yxwithu閱讀 129評論 0 0
  • Given an array of integers sorted in ascending order, fin...
    matrxyz閱讀 193評論 0 0
  • 題目 Given an array of integers sorted in ascending order, ...
    時光雜貨店閱讀 143評論 0 0
  • 文/高昂 屋子是南北長,我的床在最北頭,窗戶在最南頭,不知道外面是月光還是燈光,能從最南頭照到屋里最北邊的墻上,和...
    公園閱讀 158評論 0 0