问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3732 访问。

给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元素的情况下,该数组能否变成一个非递减数列。

我们是这样定义一个非递减数列的: 对于数组中所有的 i (1 <= i < n),满足 array[i] <= array[i + 1]。

输入: [4,2,3]

输出: True

解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。

输入: [4,2,1]

输出: False

解释: 你不能在只改变一个元素的情况下将其变为非递减数列。

说明:  n 的范围为 [1, 10,000]。


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

Input: [4,2,3]

Output: True

Explanation: You could modify the first 4 to 1 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.

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


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3732 访问。

public class Program {

    public static void Main(string[] args) {
int[] nums = null; nums = new int[] { 4, 2, 3 };
var res = CheckPossibility(nums);
Console.WriteLine(res); Console.ReadKey();
} private static bool CheckPossibility(int[] nums) {
//当发现逆序时,根据更后面1个值决定把当前值变成后面的
//还是把后面的值变成前面的,最后判定数组是否升序即可
for(int i = 0; i < nums.Length - 1; i++) {
if(nums[i] > nums[i + 1]) {
if(i + 2 < nums.Length && nums[i + 2] < nums[i]) {
nums[i] = nums[i + 1];
} else {
nums[i + 1] = nums[i];
}
return IsSortedArray(nums);
}
}
return true;
} private static bool IsSortedArray(int[] nums) {
//判断数组是否升序
for(int i = 0; i < nums.Length - 1; i++) {
if(nums[i] > nums[i + 1]) return false;
}
return true;
} }

以上给出1种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3732 访问。

True

分析:

显而易见,以上算法的时间复杂度为:  。

最新文章

  1. Linux平台 Oracle 10gR2(10.2.0.5)RAC安装 Part1:准备工作
  2. 浏览器内部工作原理--作者:Tali Garsiel
  3. 西门子成立next47部门,斥资十亿欧元投资VR/AR等初创公司
  4. C语言模块化编译介绍
  5. 【C++】递增递减操作符与指针的关系
  6. error MSB4019: 未找到导入的项目“C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\WebApplications\Microsoft.WebApplication.targets”
  7. Unity胶囊体的碰撞检测实现
  8. Tkinter教程之Radiobutton篇
  9. z-index的最大值、最小值
  10. ios常用的框架(源自知乎上的回答)
  11. STL deque详解
  12. 【Eclipse】修改项目访问名称
  13. Servlet&amp;&amp;Jsp 概述
  14. 单例模式、简单工厂模式、XML解析
  15. cmake教程
  16. LeetCode 695 岛屿的最大面积
  17. 安卓ViewStub用法
  18. linux学习笔记-grub模式引导进入系统
  19. JSP 性能优化
  20. LeetCode初级算法的Python实现--排序和搜索、设计问题、数学及其他

热门文章

  1. J.U.C体系进阶(四):juc-sync 同步器框架
  2. 耐心看,1个Dubbo漏洞,35道必问面试题,Dubbo没什么可神秘的
  3. Python协程之Gevent模块
  4. Java继承多态
  5. 转载 npm 安装vue出现的问题
  6. vue中引入jq的步骤--以及注意事项
  7. String字符串缓冲区、StringBuffer
  8. 选择排序的实现以及如何编写测试 #CS61B-sp18-3.1
  9. Ionic 警告框
  10. Day07_品牌管理