[leetcode]162 Find Peak Element

Source: Internet
Author: User

https://oj.leetcode.com/problemset/algorithms/

Http://siddontang.gitbooks.io/leetcode-solution/content/array/find_peak_element.html

Public class solution {    public int findpeakelement (int[]  NUM)  {                //  solution a:        return findpeakelement_binary (num);                 //  Solution b:        // return findpeakelement_gready (num );    }    /////////////////////    //  solution a: binary    //    public int  Findpeakelement_binary (Int[] num)     {         int low = 0;        int high =  num.length - 1;        while  (Low <= high)          {            int mid = low  +  (High - low)  / 2;                         if  (mid ==  0 | | &NBSP;NUM[MID]&NBSP;&GT;=&NBSP;NUM[MID&NBSP;-&NBSP;1])  &&                  (mid == num.length - 1 | | &NBSP;NUM[MID]&NBSP;&GT;=&NBSP;NUM[MID&NBSP;+&NBSP;1])              {                 return mid;            }             else if  (mid > 0 &&  Num[mid - 1] >= num[mid])              {                 high = mid - 1;            }             else             {                 low = mid + 1;             }        }         return num[low];    }         /////////////////////    // solution a: gready    //     Public int findpeakelement_gready (Int[] num)     {         // Iterate every elements, if it is greater  than its neighbours, return the value.         if  (num == null | |  num.length == 0)             return  -1; // The input array cannot be null         if  (num.length == 1)              return 0; // A edge case.                     for  (int i = 0 ; i < num.length ; i ++)          {            int cur  = num[i];            int pre  = i == 0 ? integer.min_value : num[i - 1];             int next = i == num.length  - 1 ? Integer.MIN_VALUE : num[i + 1];             if  (cur > pre && cur >  next)             {                 return i;             }        }         // no i did ' t find it.        //  it is possible that all numbers are the same         return -1;    }}


[leetcode]162 Find Peak Element

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.