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

來源:互聯網
上載者:User
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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.