博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
665. Non-decreasing Array(python+cpp)
阅读量:3700 次
发布时间:2019-05-21

本文共 1646 字,大约阅读时间需要 5 分钟。

题目:

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].

解释:

判断数组是否能在改变最多一个数字的情况下变成非递减序列。
当遇到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
& nums) {
bool modified=false; for (int i=0;i
nums[i+1]) {
if(modified) return false; if(i<1 || nums[i-1]

总结:

转载地址:http://yrlcn.baihongyu.com/

你可能感兴趣的文章
贝叶斯算法原理简介
查看>>
支持向量机算法原理简介
查看>>
推荐系统简介
查看>>
降维处理:PCA和LDA
查看>>
EM算法
查看>>
KNN算法简介
查看>>
线性分类
查看>>
Softmax分类器及最优化
查看>>
神经网络原理简介
查看>>
卷积神经网络原理简介
查看>>
TensorFlow基本计算单元:代码示例
查看>>
TensorFlow常用操作:代码示例
查看>>
线性回归:代码实现
查看>>
Mnist数据集简介
查看>>
逻辑回归:代码实现
查看>>
神经网络:代码实现
查看>>
卷积神经网络:代码实现
查看>>
模型数据的保存和读取
查看>>
运算符重载
查看>>
软件工程复习笔记 第六章 --编码
查看>>