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 };

    二分查找

  • 相关阅读:
    C++中两种获取UUID的方法(编程)
    在python中发送自定义消息
    lib,dll的位置
    GetWindowText
    SuspendThread and ResumeThread
    创建线程检查按钮的状态
    C++检测句柄的权限
    POJ2186 强联通
    POJ2186 强联通
    POJ 1201 差分约束(集合最小元素个数)
  • 原文地址:https://www.cnblogs.com/abc-begin/p/7706708.html
Copyright © 2011-2022 走看看