find peaks
Topic description: A peak element is an element whose value is greater than its left and right neighbors.
Given an input array nums, find the peak element and return its index. The array may contain multiple peaks, in which case the position of any one of the peaks is returned.
You can assume nums[-1] = nums[n] = -∞ .
For example descriptions, please refer to the official website of LeetCode.
Source: LeetCode
Link: https://leetcode-cn.com/problems/find-peak-element/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.
Solution 1: Array Traversal
First, judge two special cases:
- If there is only one element, return the index bit of the first element directly;
- If there are two elements, the corresponding index bits are directly returned according to the size of the two elements.
If the array nums has more than 2 elements, traverse from the first element to determine whether it is a peak:
- First judge the first digit of the array, if it is greater than the value of the second digit, return 0;
- Otherwise, traverse the elements from 1 to nums.length-2 to determine whether it is a peak value, and if it is a peak value, directly return the corresponding index bit;
- Finally, if no peak is found, determine whether the last element is greater than the value of the previous element, and if so, return the largest index bit, otherwise, return -1 to indicate that there is no peak.
public class LeetCode_162 {
public static int findPeakElement(int[] nums) {
// 如果只有一个元素,直接返回第一个元素的索引位
if (nums.length == 1) {
return 0;
}
// 如果有两个元素,则根据判断这两个元素的大小直接返回相应的索引位
if (nums.length == 2) {
if (nums[0] > nums[1]) {
return 0;
} else {
return 1;
}
}
// 特殊判断数组的第一位,如果大于第二位的值,则返回0
if (nums[0] > nums[1]) {
return 0;
}
int index = 1;
// 遍历从1到nums.length-2的元素,判断是否是峰值
for (; index < nums.length - 1; index++) {
if (nums[index] > nums[index - 1]) {
if (nums[index] > nums[index + 1]) {
return index;
}
} else {
if (nums[index] > nums[index + 1]) {
index++;
}
}
}
// 如果前面没有找到峰值,判断最后一个元素是否大于前面的一个元素值,如果是,则返回最大的索引位,否则,返回-1表示没有峰值
if (nums[nums.length - 1] > nums[nums.length - 2]) {
return nums.length - 1;
} else {
return -1;
}
}
public static void main(String[] args) {
int[] nums = new int[]{1, 2, 1, 3, 5, 6, 4};
// 测试用例,期望返回值: 1或5
System.out.println(findPeakElement(nums));
}
}
[Daily Message] If you want to make this money, you have to suffer this hardship. To be a strong person in life, you can't care about gains and losses.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。