友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
162. Find Peak Element
A peak element is an element that is greater than its neighbors.
Given an input array nums
, where nums[i] ≠ nums[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 nums[-1] = nums[n] = -∞
.
Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = `[`1,2,1,3,5,6,4] Output: 1 or 5 Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
Note:
Your solution should be in logarithmic complexity.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Find Peak Element.
*
* Memory Usage: 38.4 MB, less than 100.00% of Java online submissions for Find Peak Element.
*
* Copy form: https://leetcode.com/problems/find-peak-element/solution/[Find Peak Element solution - LeetCode]
*/
public int findPeakElement(int[] nums) {
return search(nums, 0, nums.length - 1);
}
private int search(int[] nums, int low, int high) {
if (low == high) {
return low;
}
int mid = (low + high) / 2;
if (nums[mid] < nums[mid + 1]) {
return search(nums, mid + 1, high);
}
return search(nums, low, mid);
}
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Find Peak Element.
*
* Memory Usage: 38.8 MB, less than 100.00% of Java online submissions for Find Peak Element.
*/
public int findPeakElementLinearScan(int[] nums) {
if (Objects.isNull(nums) || nums.length == 0) {
return -1;
}
for (int i = 0; i < nums.length; i++) {
if (isPeak(nums, i)) {
return i;
}
}
return -1;
}
private boolean isPeak(int[] nums, int index) {
if (0 < index - 1 && nums[index - 1] > nums[index]) {
return false;
}
if (index + 1 < nums.length && nums[index] < nums[index + 1]) {
return false;
}
return true;
}