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 }
  • 相关阅读:
    python迭代器与iter()函数实例教程
    手动安装python后,交互模式下退格键乱码
    find参数exec、管道符|、xargs的区别
    比较好的网址收集
    sed小知识总结
    irc操作小记
    irssi忽略退出,加入消息
    Web自动化简介
    android&ios区别
    移动自动化应用展望
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4154583.html
Copyright © 2011-2022 走看看