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

LeetCode-Search for a Range

編輯:C++入門知識

LeetCode-Search for a Range


 

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].

解題分析:就是一個二分搜索的應用,不難。但是就是注意一個數組越界的檢查。LeetCode自己的編譯器會報錯。

 

int a,b;
 a=num;
 b=num;
while(A[a] == target )  a--;
while(A[b] == target )  b++;
最開始的時候,代碼是這樣的,對二分搜索找到了target,再進行往前往後的找。在codeblocks上運行是無錯, 但就是提交在LeetCode上面會出現問題。

 

最後做了一個數組的溢出判斷,終於AC了

 

int a,b;
        a=num;
        b=num;
        while(A[a] == target && a >= 0)  a--;
        while(A[b] == target && b <= n-1)  b++;

 

 

 

 

class Solution {
private: int binary_search(int* a, int len, int goal)
    {
    int low = 0;
    int high = len - 1;
    while(low <= high)
    {
        int middle = (low + high)/2;
        if(a[middle] == goal)
            return middle;
        else if(a[middle] > goal)
            high = middle - 1;
        else
            low = middle + 1;
    }
    return -1;
    }

public:
    vector searchRange(int A[], int n, int target) {
        vector s;
        int num = binary_search(A,n,target);
        if(num == -1) {s.push_back(-1);s.push_back(-1);}
        else {
        int a,b;
        a=num;
        b=num;
        while(A[a] == target && a >= 0)  a--;
        while(A[b] == target && b <= n-1)  b++;
        s.push_back((++a));
        s.push_back((--b));
        }
        return s;
    }
};


 

 




 

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