程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode 34 Search for a Range

LeetCode 34 Search for a Range

編輯:C++入門知識

LeetCode 34 Search for a Range


翻譯

給定一個整型已排序數組,找到一個給定值在其中的起點與終點。

你的算法復雜度必須低於O(logn)。

如果目標在數組中不會被發現,返回[-1, -1]。

例如,給定[5, 7, 7, 8, 8, 10],目標值為8,返回[3, 4]。

原文

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 searchRange(vector &nums, int target) {
        vector res;
        int l = 0, r = nums.size() - 1;
        if(nums.size() <= 0) {
            res.push_back(-1);
            res.push_back(-1);
            return res;     
        } else if(nums.size() == 1) {
            if(nums[0] == target) {
                res.push_back(0);
                res.push_back(0);
                return res;
            } else {
                res.push_back(-1);
                res.push_back(-1);
                return res;
            }
        }
        while(l <= r) {
            if(nums[l] < target) {
                ++l;
            } 
            if(nums[r] > target) {
                --r;
            }
            if(nums[l] == target && nums[r] == target) {
                res.push_back(l);
                res.push_back(r);
                return res;
            }
        }
        res.push_back(-1);
        res.push_back(-1);
        return res;
    }
};

隨手寫的,雖然能通過,不過還是看看大神的解法來提高自己。

class Solution {
private:
    int binarySearchLow(vector& nums, int target, int begin, int end)
    {
        if(begin > end) return begin;
        int mid = begin + (end - begin) / 2;
        if(nums[mid] < target) return binarySearchLow(nums, target, mid + 1, end);
        else return binarySearchLow(nums, target, begin, mid - 1);
    }
    int binarySearchUp(vector& nums, int target, int begin, int end)
    {
        if(begin > end) return end;
        int mid = begin + (end - begin) / 2;
        if(nums[mid] > target) return binarySearchUp(nums, target, begin, mid - 1);
        else return binarySearchUp(nums, target, mid + 1, end);
    }
public:
    vector searchRange(vector& nums, int target) {
        vector res(2, -1);
        if(nums.empty()) return res;
        int high = binarySearchUp(nums, target, 0, nums.size() -1);
        int low = binarySearchLow(nums, target, 0, nums.size() - 1);
        if(high >= low)
        {
            res[0] = low;
            res[1] = high;
            return res;
        }
        return res;
    }
};

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved