Skip to content

Commit afddd2b

Browse files
authored
Create 915._Partition_Array_into_Disjoint_Intervals.md
1 parent 8994538 commit afddd2b

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# 915. Partition Array into Disjoint Intervals
2+
3+
**<font color=red>难度: Medium</font>**
4+
5+
## 刷题内容
6+
7+
> 原题连接
8+
9+
* https://leetcode.com/contest/weekly-contest-104/problems/partition-array-into-disjoint-intervals/
10+
11+
> 内容描述
12+
13+
```
14+
Given an array A, partition it into two (contiguous) subarrays left and right so that:
15+
16+
Every element in left is less than or equal to every element in right.
17+
left and right are non-empty.
18+
left has the smallest possible size.
19+
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
20+
21+
22+
23+
Example 1:
24+
25+
Input: [5,0,3,8,6]
26+
Output: 3
27+
Explanation: left = [5,0,3], right = [8,6]
28+
Example 2:
29+
30+
Input: [1,1,1,0,6,12]
31+
Output: 4
32+
Explanation: left = [1,1,1,0], right = [6,12]
33+
34+
35+
Note:
36+
37+
2 <= A.length <= 30000
38+
0 <= A[i] <= 10^6
39+
It is guaranteed there is at least one way to partition A as described.
40+
```
41+
42+
## 解题方案
43+
44+
> 思路 1
45+
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******
46+
47+
48+
49+
50+
用前缀最大数组与后缀最大数组做,满足要求的临界点是前半部分的最大值刚好由大于变成了小于等于后半部分的最小值
51+
52+
```python
53+
class Solution(object):
54+
def partitionDisjoint(self, A):
55+
"""
56+
:type A: List[int]
57+
:rtype: int
58+
"""
59+
if not A or len(A) == 0:
60+
return 0
61+
62+
max_num, min_num = A[0], A[-1]
63+
max_prefix, min_suffix = [max_num], [min_num]
64+
for i in range(1, len(A)):
65+
max_num = max(A[i], max_num)
66+
max_prefix.append(max_num)
67+
for i in range(len(A)-2, -1, -1):
68+
min_num = min(A[i], min_num)
69+
min_suffix.insert(0, min_num)
70+
idx = 0
71+
while max_prefix[idx] > min_suffix[idx+1]:
72+
idx += 1
73+
return idx + 1
74+
```
75+
76+
77+
78+
79+
80+
81+
82+
83+
84+
85+
86+
87+
88+

0 commit comments

Comments
 (0)