标签:leetcode
A peak element is an element that is greater than its neighbors.思路1: 遍历,O(N)
代码1:
public int findPeakElement1(int[] num) {//暴力 for(int i = 0; i < num.length; ++i){ if(i+1 < num.length){ if(num[i] > num[i+1] && ((i -1 >= 0 && num[i] > num[i-1])||(i-1 < 0))){ return i; } }else { if(i-1 < 0 || i -1 >=0 && num[i] > num[i-1]){ return i; } } } return 0; }思路2:二分,
public int findPeakElement(int[] num) {// int l = 0, r = num.length - 1, mid; while (l < r){ mid = l + (r - l) / 2; if(num[mid] < num[mid + 1]) l = mid + 1; else r = mid; } return num[l]; }
标签:leetcode
原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/44889115