665. Non-decreasing Array
665.1 题目描述:
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 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].
665.2 解题思路:
思路一:复制一份nums为temp。设置计数器count=0。从i=0到i=nums.size()-1遍历nums,当我们发现当前节点比下一个节点大时,count++。如果i不是0,则尝试修改当前节点,将当前节点变小,并且将i-=2,回溯比较,以防当前节点的前一个节点比后一个节点大。遍历结束时,如果count小于2,则可返回true。count重置为0。从i=0到i=nums.size()-1遍历temp,当我们发现当前节点比下一个节点大时,count++,并尝试修改当前节点的下一个节点,使其变大。遍历结束时,如果count小于2,则可返回true。没有发生返回,则返回Ffalse。
思路二:设置计数器count=0。从i=1到i=nums.size()遍历nums。nums[i-1]>nums[i]时,修改数组不外乎有两种情况,使其中大的变成跟小的一样,或者使其小的变成跟大的一样。变大无所谓,对前面的顺序不会发生影响。但变小的话,容易对前面的序列发生影响,比如nus[i-2]>nums[i],这样的话,如果是这种情况,或者i==1,则进行改小,其余的情况都进行改大。当count大于2时,直接返回false。否则为true。
思路三:对nums数组复制两份a1,a2。其中一份改大,另一份改小,且只改动一次就直接break,结束遍历。然后a1和对a1进行排序后进行比较,a2和对a2进行排序后进行比较,只要其中一个是相等的,就可返回true,否则返回false。这种Python写起来比较方便。
665.3 C++代码:
1、思路一代码(39ms):
class Solution136 {
public:
bool checkPossibility(vector<int>& nums) {
if (nums.size() < 2)
return true;
int count = 0;
vector<int>temp = nums;
for (int i = 0; i < nums.size() - 1; i++)
{
if (nums[i]>nums[i + 1])
{
if (i != 0)
{
nums[i] = nums[i + 1];
i-=2;
}
count++;
}
}
if (count<2)
return true;
count = 0;
for (int i = 0; i < temp.size() - 1; i++)
{
if (temp[i]>temp[i + 1])
{
temp[i + 1] = temp[i];
count++;
}
}
if (count < 2)
return true;
return false;
}
};
2、思路二代码(46ms)
class Solution136_1 {
public:
bool checkPossibility(vector<int>& nums) {
if (nums.size() < 2)
return true;
int count = 0;
for (int i = 1; i < nums.size() && count<2 ;i++)
{
if (nums[i-1]>nums[i])
{
count++;
if (i == 1 || nums[i - 2] <= nums[i])
nums[i - 1] = nums[i];
else
nums[i] = nums[i - 1];
}
}
if (count < 2)
return true;
else
return false;
}
};
665.4 Python代码:
2、思路二代码(55ms)
class Solution(object):
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums)<2:
return True
count=0
for i in range(1,len(nums)):
if nums[i-1]>nums[i]:
count+=1
if i==1 or nums[i-2]<=nums[i]:
nums[i-1]=nums[i]
else:
nums[i]=nums[i-1]
if count>1:
return False
return True
3、思路三代码(108ms)
class Solution1(object):
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums)<2:
return True
a1=nums[:]
a2=nums[:]
for i in range(len(nums)-1):
if nums[i]>nums[i+1]:
a1[i]=nums[i+1]
a2[i+1]=nums[i]
break
return a1==sorted(a1) or a2==sorted(a2)