LeetCode周赛#104 Q2 Partition Array into Disjoint Intervals (枚举)

题目来源:https://leetcode.com/contest/weekly-contest-104/problems/partition-array-into-disjoint-intervals/

问题描述

915. Partition Array into Disjoint Intervals

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:

  1. 2 <= A.length <= 30000
  2. 0 <= A[i] <= 10^6
  3. It is guaranteed there is at least one way to partition A as described.

------------------------------------------------------------

题意

给定一个数列A,将数列A从某处分开,使得左边数列的最大值小于等于右边数列的最小值。求满足条件的左边数列的最小长度。

------------------------------------------------------------

思路

枚举左边数列的长度,判断是否满足题设条件。可以用O(n)求出max(A[0:i])和min(A[i:len-1]), i=0,1,2,…,len-1,用于判断是否满足条件。由于问题没有单调性,因此只能使用线性查找不能用二分查找。

------------------------------------------------------------

代码

class Solution {
public:
    vector<int> lmax;
    vector<int> rmin;

    void init(vector<int> &A)
    {
        int i, len = A.size();
        lmax.clear();
        lmax.push_back(A[0]);
        for (i=1; i<len; i++)
        {
            lmax.push_back(max(lmax.back(), A[i]));
        }
        rmin.clear();
        rmin.push_back(A[len-1]);
        for (i=len-2; i>=0; i--)
        {
            rmin.push_back(min(rmin.back(), A[i]));
        }
    }
    
    int partitionDisjoint(vector<int>& A) {
        init(A);
        int i, len = A.size();
        for (i=0; i<len-1; i++)
        {
            if (lmax[i] <= rmin[len-2-i])
            {
                return i+1;
            }
        }
    }
};

猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/82942491