Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.
We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).
Example 1:
Input: [4,2,3] Output: True Explanation: You could modify the first4 to1 to get a non-decreasing array.
Example 2:
Input: [4,2,1] Output: False Explanation: You can't get a non-decreasing array by modify at most one element.
Note: The n belongs to [1, 10,000].
<Solution>想法如下
- 找到數字變小的地方,不難,就是按順序歷遍找就好。假設 nums[i-1] > nums[i]
- 比較難的地方是,要怎麼修正。如果數列長度小於 2,那直接修正其一即可
- 數列長度大於等於2,然後 nums[i-2] 小於等於 nums[i],那就只要把 nums[i-1] 改成 nums[i] 就好
- 數列長度大於等於2,然後 nums[i-2] 大於 nums[i],那麼就要把 nums[i] 改成 nums[i-1]
- 改完後繼續歷遍,最後的 cnt 如果大於 1,就回傳 false,反之回傳 true
Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public boolean checkPossibility(int[] nums) { | |
int cnt = 0; | |
for(int i = 1; i < nums.length; i++) { | |
if(nums[i - 1] > nums[i]) { | |
++cnt; | |
if(i-2 < 0 || nums[i-2] <= nums[i]) { | |
nums[i-1] = nums[i]; | |
} | |
else { | |
nums[i] = nums[i-1]; | |
} | |
} | |
} | |
return cnt <= 1; | |
} | |
} |
沒有留言:
張貼留言