[LeetCode]162 Find Peak Element
2015-01-09 16:51
405 查看
https://oj.leetcode.com/problemset/algorithms/
http://siddontang.gitbooks.io/leetcode-solution/content/array/find_peak_element.html
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
- Leetcode_162_Find Peak Element
- LeetCode(162) Find Peak Element
- Leetcode[162]-Find Peak Element
- 【leetcode】【162】Find Peak Element
- (leetcode162)find peak element
- Leetcode_162_Find Peak Element
- leetcode[162]Find Peak Element
- leetcode 162: Find Peak Element
- LeetCode 162 Find Peak Element
- LeetCode[162] Find Peak Element
- leetcode162: Find Peak Element
- leetcode 162 —— Find Peak Element
- leetcode162---Find Peak Element(找峰值点)
- 【leetcode】Array——Find Peak Element(162)
- Leetcode #162 Find Peak Element
- Leetcode 162: Find Peak Element
- leetcode-162-Find Peak Element
- LeetCode162——Find Peak Element
- 【LEETCODE】162-Find Peak Element [Python]