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 }
  • 相关阅读:
    win10+PHP 安装memcache
    win10+PHP 安装redis
    一个github搞定微信小程序支付系列
    Linux下新建一个站点
    Linux下更改mysql版本
    零基础配置Linux服务器环境
    手把手教你使用ueditor
    react学习三
    react学习二 生命周期
    window.location.replace和window.location.href区别
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4154583.html
Copyright © 2011-2022 走看看