题目:
Given an array
A
, partition it into two (contiguous) subarraysleft
andright
so that:
Every element inleft
is less than or equal to every element inright
.
left
andright
are non-empty.
left
has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
Example 1:Input: [5,0,3,8,6] Output: 3 Explanation: left = [5,0,3], right =[8,6]
Example 2:
Input: [1,1,1,0,6,12] Output: 4 Explanation: left = [1,1,1,0], right =[6,12]
Note:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
It is guaranteed there is at least one way to partition
A
as described.
解释:
要保持相对顺序
假设left
是[:partitionIdx](包括partitionIdx)
,这部分的最大值就是localMax
,假设这是一个正确的分割,那么partitionIdx
到end
的所有的值都是>=localMax
的,但是如果我们在right
部分找到了一个a[i]<localMax
,那么就证明当前的分割是不正确的,这表示我们要把a[i]
加到左边,也就是partitionIdx
需要更新成i
,而且我们需要重新计算left部分的 最大值,如果当前max大于localMax,但是没有a[i]<localMax了,则无需更新localMax,此时a[i]就是右边的部分,max也是右边的部分,a[i]可以比max小,loacalMax是左边部分的最大值,注意一定不能直接在else里面更新localMax。
python代码:
class Solution:
def partitionDisjoint(self, A):
"""
:type A: List[int]
:rtype: int
"""
partitionIdx=0
localMax=A[0]
_max=localMax
for i in range(1,len(A)):
if A[i]<localMax:
partitionIdx=i
localMax=_max
else:
_max=max(_max,A[i])
return partitionIdx+1
c++代码:
class Solution {
public:
int partitionDisjoint(vector<int>& A) {
int partitionIdx=0;
int localMax=A[0];
int _max=localMax;
for (int i=0;i<A.size();i++)
{
if(A[i]<localMax)
{
partitionIdx=i;
localMax=_max;
}
else
_max=max(_max,A[i]);
}
return partitionIdx+1;
}
};
总结: