1. 程式人生 > >LeetCode Day28 Search for a Range

LeetCode Day28 Search for a Range

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int left=0,right=nums.size()-1,mid;
        while(left<=right){
            mid=(left+right)/2;
            
            if(target==nums[mid]){
                int i=mid,j=mid;
                while
(target==nums[i-1]&&i>0) i--; while(target==nums[j+1]&&j<nums.size()-1) j++; return {i,j}; } else if(target>nums[mid]) left=mid+1; else right=mid-1; } return {-1,-1}; } };

上面的演算法不是嚴格意義上的O(logn)的演算法,因為在最壞的情況下會變成O(n),比如當數組裡的數全是目標值的話,從中間向兩邊找邊界就會一直遍歷完整個陣列,那麼我們下面來看一種真正意義上的O(logn)的演算法,使用兩次二分查詢法,第一次找到左邊界,第二次呼叫找到右邊界即可,具體程式碼如下:

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        if(nums.empty()) return {-1,-1};
        vector<int> res(2, -1);
        int left = 0, right = nums.size() - 1;
        while (left < right) {
            int mid = left + (right -
left) / 2; if (nums[mid] < target) left = mid + 1; else right = mid; } if (nums[right] != target) return res; res[0] = right; right = nums.size()-1; while (left < right) { int mid =(right + left) / 2+1;//整型除法只會向下取整,現改為向上取整,保證中間值一直>left,可以一直向右檢查 if (nums[mid] == target) left = mid;//只存在>或==的情況 else right= mid-1; } res[1] = left; return res; } };