zoukankan      html  css  js  c++  java
  • 162. Find Peak Element

    162. Find Peak Element【medium】

    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.

    click to show spoilers.

    Note:

    Your solution should be in logarithmic complexity.

    解法一:

     1 class Solution {  
     2 public:  
     3     int findPeakElement(const vector<int> &num) {  
     4         for (int i = 1; i < num.size(); i++) {  
     5             if (num[i] < num[i - 1]) {
     6                 return i - 1;  
     7             }                 
     8         }  
     9         
    10         return num.size() - 1;  
    11     }  
    12 }; 

    直接顺序遍历

    解法二:

     1 class Solution {
     2 public:
     3     int findPeakElement(vector<int>& nums) {        
     4         int start = 0;
     5         int end = nums.size() - 1;
     6         
     7         while (start + 1 < end) {
     8             int mid = (end - start) / 2 + start;
     9             
    10             if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) {
    11                 return mid;
    12             }
    13             /* 如果中间的数比后一位数大的话,peek点肯定在mid左边或是mid */
    14             else if (nums[mid] > nums[mid + 1]) {
    15                 end = mid;
    16             }
    17             /* 如果中间的数比前一位数小的话,peek点肯定在mid右边或是mid */
    18             else {
    19                 start = mid;
    20             }
    21         }
    22         
    23         return nums[start] > nums[end] ? start : end;
    24     }
    25 };

    二分查找

  • 相关阅读:
    ios lazying load
    ios 单例模式
    ios 消息推送原理
    C#图片闪烁
    C#使窗体不显示在任务栏
    实时监测鼠标是否按下和鼠标坐标
    winfrom窗体的透明度
    C#获取屏幕的宽度和高度
    HDU 5171 GTY's birthday gift 矩阵快速幂
    HDU 5170 GTY's math problem 水题
  • 原文地址:https://www.cnblogs.com/abc-begin/p/7706708.html
Copyright © 2011-2022 走看看