前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >Leetcode 665. Non-decreasing Array

Leetcode 665. Non-decreasing Array

作者头像
Tyan
发布2021-07-08 15:53:05
发布2021-07-08 15:53:05
37500
代码可运行
举报
文章被收录于专栏:SnailTyanSnailTyan
运行总次数:0
代码可运行

文章作者:Tyan 博客:noahsnail.com | CSDN | 简书

1. Description

2. Solution

**解析:**Version 1首先对前后相邻的两个值进行比较,统计当前值nums[i]大于后值num[i+1]的次数,并保存当前值的索引index,如果一次没出现,说明当前数组为非递减数组,如果大于两次,只修改一个值的情况下不可能变为非递减数组。当只出现一次时,需要具体分析相关情况。当nums[index]位于数组第一个(0)或倒数第二(len(nums) - 2)的位置时,此时修改nums[index]即可满足非递减数组。当nums[index - 1] <= nums[index + 1]时,修改nums[index]可满足非递减数组。当nums[index] <= nums[index + 2]时,修改nums[index+1]可满足非递减数组。除此之外,无论是修改nums[index]还是nums[index+1]都不能变为非递减数组。

  • Version 1
代码语言:javascript
代码运行次数:0
复制
class Solution:
    def checkPossibility(self, nums: List[int]) -> bool:
        count = 0
        index = 0
        for i in range(len(nums) - 1):
            if nums[i] > nums[i + 1]:
                count += 1
                index = i
        if count == 0:
            return True
        elif count > 1:
            return False
        else:
            if index == 0 or index == len(nums) - 2:
                return True
            elif nums[index - 1] <= nums[index + 1]:
                return True
            elif nums[index] <= nums[index + 2]:
                return True
            else:
                return False
  • Version 2
代码语言:javascript
代码运行次数:0
复制
class Solution:
    def checkPossibility(self, nums: List[int]) -> bool:
        count = 0
        index = 0
        for i in range(len(nums) - 1):
            if nums[i] > nums[i + 1]:
                count += 1
                if count > 1:
                    return False
                index = i

        if count == 0 or index == 0 or index == len(nums) - 2 or nums[index - 1] <= nums[index + 1] or nums[index] <= nums[index + 2]:
            return True
        else:
            return False

Reference

  1. https://leetcode.com/problems/non-decreasing-array/
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/07/01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Description
  • 2. Solution
  • Reference
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档