[leetcode]915. Partition Array into Disjoint Intervals
[leetcode]915. Partition Array into Disjoint Intervals
Analysis
是阴天呢—— [每天刷题并不难0.0]
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.
Explanation:
tmp_min[i]表示A[i]到A[len-1]中最小的数,tmp_max表示A[i]前最大的数,当tmp_max <= tmp_min[i]的时候我们就可以返回i,即为左半边数组的长度。
Implement
class Solution {
public:
int partitionDisjoint(vector<int>& A) {
int len = A.size();
vector<int> tmp_min(len);
tmp_min[len-1] = A[len-1];
for(int i=len-2; i>0; i--)
tmp_min[i] = min(tmp_min[i+1], A[i]);
int tmp_max = 0;
for(int i=1; i<len; i++){
tmp_max = max(tmp_max, A[i-1]);
if(tmp_max <= tmp_min[i])
return i;
}
return len;
}
};