665. Non-decreasing Array只允許修改一位數的非遞減數組
阿新 • • 發佈:2018-04-21
you pan 修改 with 暴力 ive ret nbsp 優化
[抄題]:
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.
[暴力解法]:
時間分析:
空間分析:
[優化後]:
時間分析:
空間分析:
[奇葩輸出條件]:
[奇葩corner case]:
[思維問題]:
不知道怎麽改啊
[一句話思路]:
既然只允許修改一位,“前天”是否異常,決定了應該修改“昨天”還是“今天”
[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):
[畫圖]:
[一刷]:
- 必須要有“昨天”異常的前提才有後續的操作。所以要把“昨天”之後的全都括起來
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分鐘肉眼debug的結果]:
[總結]:
頭回見:既然只允許修改一位,“前天”是否異常,決定了應該修改“昨天”還是“今天”
[復雜度]:Time complexity: O(n) Space complexity: O(1)
[英文數據結構或算法,為什麽不用別的數據結構或算法]:
[關鍵模板化代碼]:
[其他解法]:
[Follow Up]:
[LC給出的題目變變變]:
[代碼風格] :
class Solution {View Codepublic boolean checkPossibility(int[] nums) { //cc if (nums == null || nums.length == 0) { return false; } //ini int count = 0; //for loop for (int i = 1; i < nums.length && count <= 1; i++) { if (nums[i - 1] > nums[i]) {count++; if (i - 2 < 0 || nums[i - 2] < nums[i]) { nums[i - 1] = nums[i]; }else { nums[i] = nums[i - 1]; }} } //return count <= 1 return count <= 1; } }
665. Non-decreasing Array只允許修改一位數的非遞減數組