zoukankan      html  css  js  c++  java
  • LeetCode

    Find Peak Element

    2015.1.23 14:28

    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.

    The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

    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.

    Solution1:

      Here is the O(n) solution.

    Accepted code:

     1 // 1CE, 2WA, 1AC, how to achieve logN with unordered data?
     2 class Solution {
     3 public:
     4     int findPeakElement(const vector<int> &num) {
     5         int n = (int)num.size();
     6 
     7         if (n == 1) {
     8             return 0;
     9         }
    10         
    11         if (num[0] > num[1]) {
    12             return 0;
    13         }
    14         
    15         if (num[n - 1] > num[n - 2]) {
    16             return n - 1;
    17         }
    18         
    19         int i;
    20         for (i = 1; i < n - 1; ++i) {
    21             if (num[i] > num[i - 1] && num[i] > num[i + 1]) {
    22                 return i;
    23             }
    24         }
    25     }
    26 };

    Solution2:

      I came up with the log(n) solution at last. See the code below.

    Accepted code:

     1 // 2WA, 1AC, the O(log(n)) solution
     2 class Solution {
     3 public:
     4     int findPeakElement(vector<int> &nums) {
     5         int n = nums.size();
     6         if (n == 1) {
     7             return 0;
     8         }
     9         
    10         int ll, rr, mm;
    11         
    12         ll = 0;
    13         rr = n - 1;
    14         while (rr - ll >= 2) {
    15             mm = (ll + rr) / 2;
    16             if (nums[mm] > nums[mm - 1] && nums[mm] > nums[mm + 1]) {
    17                 return mm;
    18             } else if (nums[mm - 1] < nums[mm]) {
    19                 ll = mm;
    20             } else {
    21                 rr = mm;
    22             }
    23         }
    24         if (nums[0] > nums[1]) {
    25             return 0;
    26         } else {
    27             return n - 1;
    28         }
    29     }
    30 };
  • 相关阅读:
    Hadoop 的版本问题
    SSH 端口转发原理
    KM算法
    最大流算法小结
    pku 2195 KM算法求最小权二分匹配
    SAP(最短增广路算法) 最大流模板
    最大流模板
    pku 1459 最大流 SAP
    pku Drainage Ditches 简单最大流 直接套模板 注意可能有重边
    推荐:吴军 谷歌黑板报 《浪潮之颠》
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/4244171.html
Copyright © 2011-2022 走看看