Skip to content

Commit bd92a69

Browse files
committed
add the python solution of problem 0915.
1 parent cc60902 commit bd92a69

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
## 分割数组
2+
3+
### 问题描述
4+
5+
给定一个数组 A,将其划分为两个不相交(没有公共元素)的连续子数组 left 和 right, 使得:
6+
7+
- left 中的每个元素都小于或等于 right 中的每个元素。
8+
- left 和 right 都是非空的。
9+
- left 要尽可能小。
10+
11+
在完成这样的分组后返回 left 的长度。可以保证存在这样的划分方法。
12+
13+
**示例1:**
14+
```
15+
输入:[5,0,3,8,6]
16+
输出:3
17+
解释:left = [5,0,3],right = [8,6]
18+
```
19+
**示例2:**
20+
```
21+
输入:[1,1,1,0,6,12]
22+
输出:4
23+
解释:left = [1,1,1,0],right = [6,12]
24+
```
25+
**提示:**
26+
- 2 <= A.length <= 30000
27+
- 0 <= A[i] <= 10^6
28+
- 可以保证至少有一种方法能够按题目所描述的那样对 A 进行划分。
29+
30+
### 解法
31+
从左到右遍历数组,维持三个标志,即left的结束位置`loc`、left中最大的值`vmx`、数组的第`0`位与访问位置之间最大的值`mx`。每次访问一个位置,若其值大于`mx`,则应将其值赋予`mx`,若其值小于`vmx`,则应将其位置赋予`loc`、将`mx`赋予`vmx`
32+
```python
33+
class Solution:
34+
def partitionDisjoint(self, A):
35+
loc = 0
36+
vmx = A[0]
37+
mx = A[0]
38+
for i, el in enumerate(A):
39+
if el > mx:
40+
mx = el
41+
if el < vmx:
42+
loc = i
43+
vmx = mx
44+
return loc + 1
45+
```
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution:
2+
def partitionDisjoint(self, A):
3+
"""
4+
:type A: List[int]
5+
:rtype: int
6+
"""
7+
loc = 0
8+
vmx = A[0]
9+
mx = A[0]
10+
for i, el in enumerate(A):
11+
if el > mx:
12+
mx = el
13+
if el < vmx:
14+
loc = i
15+
vmx = mx
16+
return loc + 1

0 commit comments

Comments
 (0)