给定一个数组 A,将其划分为两个不相交(没有公共元素)的连续子数组 left 和 right, 使得:
left 中的每个元素都小于或等于 right 中的每个元素。
left 和 right 都是非空的。
left 要尽可能小。
在完成这样的分组后返回 left 的长度。可以保证存在这样的划分方法。
示例 1:
输入:[5,0,3,8,6]
输出:3
解释:left = [5,0,3],right = [8,6]
示例 2:
输入:[1,1,1,0,6,12]
输出:4
解释:left = [1,1,1,0],right = [6,12]
链接:https://leetcode.com/problems/partition-array-into-disjoint-intervals/
解题思路:
用两个变量,left_max记录左边数组的最大值,cur_max记录遍历过的最大值。当出现比left_max小的元素时,将左边数组延长至当前位置,并把cur_max赋给left_max,否则更新cur_max的值。
代码如下:
class Solution(object):
def partitionDisjoint(self, A):
"""
:type A: List[int]
:rtype: int
"""
res = 0
left_max = cur_max = A[0]
for i in range(1, len(A)):
if left_max > A[i]:
res = i
left_max = cur_max
else:
cur_max = max(cur_max, A[i])
return res + 1
Time: O(N)
Space: O(1)
难度:中等