zoukankan      html  css  js  c++  java
  • Leetcode-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.

    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.

    Credits:
    Special thanks to @ts for adding this problem and creating all test cases.

    Analysis:

    binary search. Three pointers:start,mid,end.

    if A[mid]<A[start/end] then exsits peak on the side start/end.

    if A[mid]> both, then if A[mid]<A[mid-1], then on the side of start, otherwise, on the side of end.

    Solution:

     1 public class Solution {
     2     public int findPeakElement(int[] num) {
     3         if (num.length==0) return -1;
     4 
     5         int start = 0, end = num.length-1;
     6         while ( (end-start)>1 ){
     7             int mid = (start+end)/2;
     8             if (num[mid]>num[mid-1] && num[mid]>num[mid+1]) return mid;
     9 
    10             if (num[mid]<num[start]){
    11                 end = mid-1;
    12                 continue;
    13             }
    14 
    15             if (num[mid]<num[end]){
    16                 start = mid+1;
    17                 continue;
    18             }
    19 
    20             if (num[mid]<num[mid-1]){
    21                 end = mid-1;
    22                 continue;
    23             } else {
    24                 start = mid+1;
    25                 continue;
    26             }
    27         }
    28 
    29         if (start==end) return start;
    30 
    31         if (num[start]>num[end]) return start;
    32         else return end;            
    33         
    34     }
    35 }
  • 相关阅读:
    How to use my view helpers in my ActionMailer views?
    大败笔,状态机
    把程序进行上线部署调试了,
    支付接口心得
    rails3 正则路由
    linux下配置Mysql远程访问,不受ip限制
    ActionController::InvalidAuthenticityToken解决办法
    支付宝接口错误
    DHTML 中的绝对定位
    部署备份
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4154583.html
Copyright © 2011-2022 走看看