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,讓我們分成兩個相鄰的子數組 left 和 right,使得 left 中的所有數字小於等於 right 中的,並限定了每個輸入數組必定會有這么一個分割點,讓返回數組 left 的長度。這道題並不算一道難題,當然最簡單並暴力的方法就是遍歷所有的分割點,然后去驗證左邊的數組是否都小於等於右邊的數,這種寫法估計會超時,這里就不去實現了。直接來想優化解法吧,由於分割成的 left 和 right 數組本身不一定是有序的,只是要求 left 中的最大值要小於等於 right 中的最小值,只要這個條件滿足了,一定就是符合題意的分割。left 數組的最大值很好求,在遍歷數組的過程中就可以得到,而 right 數組的最小值怎么求呢?其實可以反向遍歷數組,並且使用一個數組 backMin,其中 backMin[i] 表示在范圍 [i, n-1] 范圍內的最小值,有了這個數組后,再正向遍歷一次數組,每次更新當前最大值 curMax,這就是范圍 [0, i] 內的最大值,通過 backMin 數組快速得到范圍 [i+1, n-1] 內的最小值,假如 left 的最大值小於等於 right 的最小值,則 i+1 就是 left 的長度,直接返回即可,參見代碼如下:
解法一:
class Solution {
public:
int partitionDisjoint(vector<int>& A) {
int n = A.size(), curMax = INT_MIN;
vector<int> backMin(n, A.back());
for (int i = n - 2; i >= 0; --i) {
backMin[i] = min(backMin[i + 1], A[i]);
}
for (int i = 0; i < n - 1; ++i) {
curMax = max(curMax, A[i]);
if (curMax <= backMin[i + 1]) return i + 1;
}
return 0;
}
};
下面來看論壇上的主流解法,只需要一次遍歷即可,並且不需要額外的空間,這里使用三個變量,partitionIdx 表示分割點的位置,preMax 表示 left 中的最大值,curMax 表示當前的最大值。思路是遍歷每個數字,更新當前最大值 curMax,並且判斷若當前數字 A[i] 小於 preMax,說明這個數字也一定是屬於 left 數組的,此時整個遍歷到的區域應該都是屬於 left 的,所以 preMax 要更新為 curMax,並且當前位置也就是潛在的分割點,所以 partitionIdx 更新為i。由於題目中限定了一定會有分割點,所以這種方法是可以得到正確結果的,參見代碼如下:
解法二:
class Solution {
public:
int partitionDisjoint(vector<int>& A) {
int partitionIdx = 0, preMax = A[0], curMax = preMax;
for (int i = 1; i < A.size(); ++i) {
curMax = max(curMax, A[i]);
if (A[i] < preMax) {
preMax = curMax;
partitionIdx = i;
}
}
return partitionIdx + 1;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/915
參考資料:
https://leetcode.com/problems/partition-array-into-disjoint-intervals/
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)