Leetcode之Non-decreasing Array 问题

来源:互联网 发布:微信怎么没有网络 编辑:程序博客网 时间:2024/06/10 01:16

问题描述:

Given an array with n integers, your task is to check if it could become non-decreasing bymodifying at most1 element.

We define an array is non-decreasing if array[i] <= array[i + 1] holds for everyi (1 <= i < n).

Note: The n belongs to [1, 10,000].

示例一:

Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to1 to get a non-decreasing array.

示例二:

Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.

问题来源:Non-decreasing Array (详细地址:https://leetcode.com/problems/non-decreasing-array/description/)

思路分析:这道题其实有一部分贪心的思想在。题目要求最多交换一次,所以我们得采用一个计数器count记录下来,count必须是不能大于等于2的,否则返回false了,接下来我们得考虑nums[i - 1]>nums[i]的情况了,当然,这样的情况我们必须得count++了,因为至少这里就需要替换一次了嘛。接下来我们考虑nums[i - 2],nums[i -1], nums[i]三个数,前提必须是nums[i-1]>nums[i]了,否则就没必要考虑替不替换了。

情况一:nums[i-1] > nums[i],nums[i-2] <= nums[i](i至少是2),比如3,6,4,5,其中nums[i-2]=3,nums[i-1]=6,nums[i]=4,nums[i+1]=5,这种情况下,我们当然是想着交换前面的num[i-1]了啊,先把它挡一挡,即nums[i-1]=nums[i]=4。其实i<2的情况下也是这种覆盖,即往“小”(数字的相对大小)了覆盖,消灭掉大的数;

情况二:nums[i-1] > nums[i],nums[i-2] > nums[i],即前面的两个数都比它大,例如3,6,2,5,nums[i-2]=3,nums[i-1]=6,nums[i]=2,nums[i+1]=5,这种情况下,我们想要抹掉的就是i本身所指向的这个数了,即nums[i],让nums[i]=nums[i-1]=6,不然的话我们就需要修改nums[i-2]和nums[i-1]两个数了,这一下不就崩了吗?所以说有点贪心的意思,我们先帮索引i所指向的数渡过难关,然后再考虑后面的情况。我把这种情况概括为往“大”了覆盖,因为不往大了覆盖实在没办法了,只能消灭掉小的数。

代码: