leet-code/src/main/java/leetcode/editor/cn/FindPeakElement.java
huangge1199@hotmail.com 04ecc22559 162:寻找峰值
2021-07-18 17:30:01 +08:00

71 lines
1.9 KiB
Java
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//峰值元素是指其值大于左右相邻值的元素。
//
// 给你一个输入数组 nums找到峰值元素并返回其索引。数组可能包含多个峰值在这种情况下返回 任何一个峰值 所在位置即可。
//
// 你可以假设 nums[-1] = nums[n] = -∞ 。
//
//
//
// 示例 1
//
//
//输入nums = [1,2,3,1]
//输出2
//解释3 是峰值元素,你的函数应该返回其索引 2。
//
// 示例 2
//
//
//输入nums = [1,2,1,3,5,6,4]
//输出1 或 5
//解释:你的函数可以返回索引 1其峰值元素为 2
//  或者返回索引 5 其峰值元素为 6。
//
//
//
//
// 提示:
//
//
// 1 <= nums.length <= 1000
// -231 <= nums[i] <= 231 - 1
// 对于所有有效的 i 都有 nums[i] != nums[i + 1]
//
//
//
//
// 进阶:你可以实现时间复杂度为 O(logN) 的解决方案吗?
// Related Topics 数组 二分查找
// 👍 466 👎 0
package leetcode.editor.cn;
//162:寻找峰值
class FindPeakElement {
public static void main(String[] args) {
//测试代码
Solution solution = new FindPeakElement().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int findPeakElement(int[] nums) {
int start = 0;
int end = nums.length - 1;
int mid = (start + end) / 2;
while (mid < nums.length - 1 && mid > 0) {
if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) {
return mid;
} else if (nums[mid] > nums[mid - 1]) {
mid++;
} else {
mid--;
}
}
return nums.length == 1 || nums[0] > nums[1] ? 0 : nums.length - 1;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}