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

LeetCode[Array]: Find Peak Element

編輯:C++入門知識

LeetCode[Array]: Find Peak Element


A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
You may imagine that num[-1] = num[n] = -∞.
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
Note:
Your solution should be in logarithmic complexity.

這個題目要求時間復雜度為O(log(N)),可以利用二分查找來做,只是這裡更新搜索區間的時候不太一樣:如果到mid的前一步是上坡而mid的下一步是下坡,那麼mid即是山頂;如果mid的前一步和後一步都是上坡,那麼山頂必然位於後半區間;如果mid的前一步和後一步都是下坡,那麼山頂必然位於前半區間。除此之外,還需要處理邊界問題。

我的C++代碼實現如下:

int findPeakElement(const vector &num) {
    int low = 0, high = num.size() - 1;
    while (low <= high) {
        int mid  = (low + high) >> 1;
        bool isUphillForward = (mid == 0 ? true : num[mid] > num[mid - 1]);
        bool isUphillAfter = (mid == num.size() - 1 ? false : num[mid + 1] > num[mid]);

        if (isUphillForward && !isUphillAfter) return mid;
        else if (isUphillForward && isUphillAfter) low = mid + 1;
        else high = mid - 1;
    }

    return low;
}


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