915. Partition Array into Disjoint Intervals(python+cpp)(略难理解)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83993655

题目:

Given an array A, partition it into two (contiguous) subarrays left and right so that:
 Every element in left is less than or equal to every element in right.
 left and right 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,假设这是一个正确的分割,那么partitionIdxend的所有的值都是>=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;
    }
};

总结:

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83993655