LeetCode周賽#104 Q2 Partition Array into Disjoint Intervals (列舉)
阿新 • • 發佈:2018-12-13
問題描述
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 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.
------------------------------------------------------------
題意
給定一個數列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;
}
}
}
};