665. Non-decreasing Array(python+cpp)
阿新 • • 發佈:2018-11-09
題目:
Given an array with
n
integers, your task is to check if it could become non-decreasing by modifying at most1
element.
We define an array is non-decreasing ifarray[i] <= array[i + 1]
holds for everyi
(1 <= i < n).
Example 1:Input: [4,2,3] Output: True Explanation: You could modify the first 4 to 1 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].
解釋:
判斷陣列是否能在改變最多一個數字的情況下變成非遞減序列。
當遇到nums[i]>nums[i+1]
的情況,我們有兩種選擇使得陣列非遞減(區域性):
1.把nums[i]
降低為nums[i+1]
2.把nums[i+1]
升高為nums[i]
如果可0.行的話,當然是選擇優先把 nums[i]
nums[i+1]
,這樣可以減少nums[i+1]
>nums[i+2]
的風險。來看一下兩種情況:
a. 1 3
5 4
6 7 --> 1 3 4 4
6 7當遇到
5>4
的情況,這裡因為4比5之前的所有數字都大,所以可以把5降為4。b. 1 4
5 3
6 7 --> 1 4 5 5
6 7當0.遇到
5>3
的情況,這裡3比5之前的4小,所以沒有選擇,只能把3 升為5。需0.要第二次改動的時候,可以直接返回false,不需要把剩下的array走完。
0。
python程式碼:
class Solution(object):
def checkPossibility (self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
modified=False
for i in range(len(nums)-1):
if nums[i]>nums[i+1]:
if modified:
return False
if i<1 or nums[i+1]>nums[i-1]:
nums[i]=nums[i+1]
else:
nums[i+1]=nums[i]
modified=True
return True
c++程式碼:
class Solution {
public:
bool checkPossibility(vector<int>& nums) {
bool modified=false;
for (int i=0;i<nums.size()-1;i++)
{
if (nums[i]>nums[i+1])
{
if(modified)
return false;
if(i<1 || nums[i-1]<nums[i+1])
nums[i]=nums[i+1];
else
nums[i+1]=nums[i];
modified=true;
}
}
return true;
}
};
總結: