• Find Peak Element 解答


    Question

    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.

    Note:

    Your solution should be in logarithmic complexity.

    Solution

    The assumption is a very good hint. It assures that there must be a peak in input array.

    We can solve this problem by Binary Search.

    Four situations to consider:

    1. nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]

    => mid is a peak

    2. nums[mid] > nums[mid - 1] && nums[mid] < nums[mid + 1]

    => There must exists a peak in right side

    3. nums[mid] < nums[mid - 1] && nums[mid] > nums[mid + 1]

    => There must exists a peak in left side

    4. nums[mid] < nums[mid - 1] && nums[mid] < nums[mid + 1]

    => Either in right or left side, there must exists a peak.

     1 public class Solution {
     2     public int findPeakElement(int[] nums) {
     3         // Binary Search to find peak
     4         int start = 0, end = nums.length - 1, mid = 0, prev = 0, next = 0;
     5         while (start + 1 < end)  {
     6             mid = (end - start) / 2 + start;
     7             prev = mid - 1;
     8             next = mid + 1;
     9             if (nums[mid] > nums[prev] && nums[mid] > nums[next])
    10                 return mid;
    11             if (nums[mid] > nums[prev] && nums[mid] < nums[next]) {
    12                 start = mid;
    13                 continue;
    14             }
    15             if (nums[mid] < nums[prev] && nums[mid] > nums[next]) {
    16                 end = mid;
    17                 continue;
    18             }
    19             start = mid;
    20         }
    21         if (nums[start] > nums[end])
    22             return start;
    23         return end;
    24     }
    25 }
  • 相关阅读:
    查看lwjgl常用状态的值
    微信公众号开发java框架:wx4j(MenuUtils篇)
    微信公众号开发java框架:wx4j(KefuUtils篇)
    微信公众号开发java框架:wx4j(MaterialUtils篇)
    微信公众号开发java框架:wx4j(入门篇)
    hashcode和equals方法小记
    https单向认证和双向认证区别
    java开发中获取路径的一些方式
    iOS使用sqlite3原生语法进行增删改查以及FMDB的使用
    IOS自动布局
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4889395.html
Copyright © 2020-2023  润新知