feat: 2025-10-28打卡
This commit is contained in:
47
162.find-peak-element.java
Normal file
47
162.find-peak-element.java
Normal file
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* @lc app=leetcode id=162 lang=java
|
||||
*
|
||||
* [162] Find Peak Element
|
||||
*/
|
||||
|
||||
// @lc code=start
|
||||
class Solution {
|
||||
public int findPeakElement(int[] nums) {
|
||||
int l = 0, r = nums.length-1, m;
|
||||
while(l <= r) {
|
||||
m = l + (r-l)/2;
|
||||
if(isPeak(m, nums)) {
|
||||
return m;
|
||||
} else if(isIncreasing(m, nums)) {
|
||||
l = m + 1;
|
||||
} else {
|
||||
r = m - 1;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("input is not valid");
|
||||
}
|
||||
|
||||
private boolean isPeak(int i, int[] nums) {
|
||||
boolean left = false, right = false;
|
||||
if(i == 0) {
|
||||
left = true;
|
||||
} else {
|
||||
left = nums[i] > nums[i-1];
|
||||
}
|
||||
if(i == nums.length-1) {
|
||||
right = true;
|
||||
} else {
|
||||
right = nums[i] > nums[i+1];
|
||||
}
|
||||
return left && right;
|
||||
}
|
||||
|
||||
private boolean isIncreasing(int i, int[] nums) {
|
||||
if(isPeak(i, nums)) {
|
||||
throw new RuntimeException("unexpected input");
|
||||
}
|
||||
return i>0?nums[i]-nums[i-1]>0:nums[i+1]-nums[i]>0;
|
||||
}
|
||||
}
|
||||
// @lc code=end
|
||||
|
||||
Reference in New Issue
Block a user