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 };
  • 相关阅读:
    函数参数太多的一种简化方法
    laravel 获取所有表名
    使用 laravel 的 queue 必须知道的一些事
    git "refusing to merge unrelated histories" 解决方法
    使用 xhprof 进行 php 的性能分析
    php 性能优化
    js原生实现轮播图效果(面向对象编程)
    nextSibling 和nextElementSibling
    如何在页面中使用svg图标
    svg动画 animate
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/4244171.html
Copyright © 2011-2022 走看看