Skip to content

Commit db7fd8f

Browse files
committed
add the solution of problem 0665.
1 parent c8c27a9 commit db7fd8f

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
## 非递减数列
2+
3+
### 问题描述
4+
5+
给定一个长度为 `n` 的整数数组,你的任务是判断在最多改变 `1` 个元素的情况下,该数组能否变成一个非递减数列。
6+
7+
我们是这样定义一个非递减数列的: 对于数组中所有的 `i(1 <= i < n)`,满足 `array[i] <= array[i + 1]`
8+
9+
**示例1:**
10+
```
11+
输入: [4,2,3]
12+
输出: True
13+
解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。
14+
```
15+
**示例2:**
16+
```
17+
输入: [4,2,1]
18+
输出: False
19+
解释: 你不能在只改变一个元素的情况下将其变为非递减数列。
20+
```
21+
**提示:**
22+
- `n` 的范围为 `[1, 10,000]`
23+
24+
### 解法
25+
26+
若数组中不存在下降的点,则其为非递减数列;若数组中存在两个下降的点,则一定不能通过改变`1`个元素来变成一个非递减数列;若数组中只存在一个下降的点,其位置为`x`,则其能通过改变`1`个元素来变成非递减数列需要满足下列任一要求:
27+
- `x`为最右的元素;
28+
- `x`为第二个元素;
29+
- `nums[x + 1] >= nums[x - 1]`
30+
- `nums[i - 2] < nums[i]`
31+
32+
```python
33+
class Solution:
34+
def checkPossibility(self, nums):
35+
if len(nums) < 2:
36+
return True
37+
count = 0
38+
for i in range(1, len(nums)):
39+
if nums[i] < nums[i - 1]:
40+
if count == 1:
41+
return False
42+
if not(i + 1 == len(nums) or nums[i + 1] >= nums[i - 1] or i - 2 < 0 or nums[i - 2] < nums[i]):
43+
return False
44+
else:
45+
count = 1
46+
return True
47+
48+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution:
2+
def checkPossibility(self, nums):
3+
"""
4+
:type nums: List[int]
5+
:rtype: bool
6+
"""
7+
if len(nums) < 2:
8+
return True
9+
count = 0
10+
for i in range(1, len(nums)):
11+
if nums[i] < nums[i - 1]:
12+
if count == 1:
13+
return False
14+
if not(i + 1 == len(nums) or nums[i + 1] >= nums[i - 1] or i - 2 < 0 or nums[i - 2] < nums[i]):
15+
return False
16+
else:
17+
count = 1
18+
return True

0 commit comments

Comments
 (0)