首页 > 代码库 > [LeetCode]162 Find Peak Element
[LeetCode]162 Find Peak Element
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 || num[mid] >= num[mid - 1]) && (mid == num.length - 1 || num[mid] >= num[mid + 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。