#leetcode#Find Peak Element
2015-07-18 16:36
375 查看
Find Peak Element
Total Accepted: 31990 TotalSubmissions: 101250My Submissions
Question
Solution
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 = -∞.
For example, in array
[1, 2, 3, 1],
3 is a peak element and your function should return the index number 2.
click to show spoilers.
Note:
Your solution should be in logarithmic complexity.
知道用binary search,但是一开始思路局限在nums[mid]要和nums[mid - 1], nums[mid + 1] 做比较来看nums[mid] 是否是 peak,这题只要返回任意一个peak就可以了, 这题给出条件 num[i] != num[i + 1], 算是个提示吧, 每次二分只要比较 nums[mid] 和 nums[mid + 1] 的大小关系就可以了
while(l < r){}, 最后返回 l 或者 r 都是可以的,因为while循环结束后 l == r
public class Solution {
public int findPeakElement(int[] nums) {
if(nums == null || nums.length == 0)
return -1;
int l = 0;
int r = nums.length - 1;
while(l < r){
int mid = l + (r - l) / 2;
if(nums[mid] > nums[mid + 1]){
r = mid;
}else{//nums[mid] < nums[mid + 1]
l = mid + 1;
}
}
return r;
}
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解