665. Non-decreasing Array - Medium
前往題目
想法
沒想法的一題,看起來很簡單,不過有好多edge case
要考慮
思路
- 走過所有
num
- 兩兩一組看,
non-decreasing
的話就直接continue
- 如果已經用了一次change就回傳false
- 如果當前的下一個比當前的上一個還大,那當前的就變成和下一個一樣大就可以了,例如
3, 5, 4
- 反之,下一個變得和當前一樣大就可以,例如
4, 5, 3
Code
class Solution {
public boolean checkPossibility(int[] nums) {
boolean changed = false;
// Go through the nums
for (int i = 0; i < nums.length - 1; ++i) {
// Base case
if (nums[i] <= nums[i + 1]) continue;
// Already used the chance
if (changed) return false;
// Use the change
if (i == 0 || nums[i + 1] >= nums[i - 1]) {
nums[i] = nums[i + 1];
} else {
nums[i + 1] = nums[i];
}
changed = true;
}
return true;
}
}
665. Non-decreasing Array - Medium
https://f88083.github.io/2024/05/29/665-Non-decreasing-Array-Medium/