LeetCode-162. Find Peak Element (JAVA)寻找peak元素

来源:互联网 发布:dns协议udp端口号 编辑:程序博客网 时间:2024/05/17 04:06

162. 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.

迭代

public int findPeakElement(int[] nums) {int lo = 0, hi = nums.length - 1;// 等号while (lo <= hi) {// 无符号右移,忽略符号位,空位都以0补齐int mid = (lo + hi) >>> 1;// 如果mid-1大,那么peak肯定在lo和mid-1之间(闭区间)if (mid - 1 >= 0 &&nums[mid] < nums[mid - 1])hi = mid - 1;// 如果mid+1大,那么peak肯定在mid+1和hi之间(闭区间)else if (mid + 1 < nums.length&& nums[mid] < nums[mid + 1])lo = mid + 1;// 其他情况(peak在开头或者结尾,或者中间)elsereturn mid;}return -1;}

递归

according to the given condition, num[i] != num[i+1], there must exist a O(logN) solution. So we use binary search for this problem.

  • If num[i-1] < num[i] > num[i+1], then num[i] is peak
  • If num[i-1] < num[i] < num[i+1], then num[i+1...n-1] must contains a peak
  • If num[i-1] > num[i] > num[i+1], then num[0...i-1] must contains a peak
  • If num[i-1] > num[i] < num[i+1], then both sides have peak
    (n is num.length)

public int findPeakElement(int[] num) {return helper(num, 0, num.length - 1);}public int helper(int[] num, int start, int end) {// 一个元素if (start == end) {return start;// 两个元素} else if (start + 1 == end) {if (num[start] > num[end])return start;return end;} else {int m = (start + end) / 2;// num[i-1] < num[i] > num[i+1], then num[i] is peakif (num[m] > num[m - 1] && num[m] > num[m + 1]) {return m;// num[i-1] < num[i] < num[i+1],// then num[i+1...n-1] must contains a peak} else if (num[m - 1] > num[m] && num[m] > num[m + 1]) {return helper(num, start, m - 1);} else {// 其他情况// 1,num[i-1] > num[i] > num[i+1],// then num[0...i-1] must contains a peak// 2,num[i-1] > num[i] < num[i+1],// then both sides have peak// 两边都可以,只需要返回右边即可,题目要求返回一个,return helper(num, m + 1, end);}}}

参考:https://discuss.leetcode.com/topic/5848/o-logn-solution-javacode

0 0