C#LeetCode刷题之#665-非递减数列( Non-decreasing Array)
问题
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 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
分析:
显而易见,以上算法的时间复杂度为: 。
最新文章
- Linux平台 Oracle 10gR2(10.2.0.5)RAC安装 Part1:准备工作
- 浏览器内部工作原理--作者:Tali Garsiel
- 西门子成立next47部门,斥资十亿欧元投资VR/AR等初创公司
- C语言模块化编译介绍
- 【C++】递增递减操作符与指针的关系
- error MSB4019: 未找到导入的项目“C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\WebApplications\Microsoft.WebApplication.targets”
- Unity胶囊体的碰撞检测实现
- Tkinter教程之Radiobutton篇
- z-index的最大值、最小值
- ios常用的框架(源自知乎上的回答)
- STL deque详解
- 【Eclipse】修改项目访问名称
- Servlet&;&;Jsp 概述
- 单例模式、简单工厂模式、XML解析
- cmake教程
- LeetCode 695 岛屿的最大面积
- 安卓ViewStub用法
- linux学习笔记-grub模式引导进入系统
- JSP 性能优化
- LeetCode初级算法的Python实现--排序和搜索、设计问题、数学及其他