题目说明
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.
分析
最核心的代码,就是找左边的最大值小于右边最小值能成立的那个分界线!
但是该算法效率不是很高,50多ms,于是提交后,找到了最快的10多ms的代码,copy后提交了,发现最快也是40ms,不知道是不是个人笔记本原因呢???思考…
[换个啥电脑呢]
代码
class Solution {
public:
int partitionDisjoint(vector<int>& A) {
int length = A.size();
int cur = 0, max = -1, min = (1e6)+1;
while(cur < length) {
if(A[cur] > max) max = A[cur];
if(A[cur] <= min) {
min = (1e6)+1;
for(int i = cur+1;i < length; ++i) {
if(A[i] < min)
min = A[i];
}
}
//look here
if(max <= min) break;
cur++;
}
return cur+1;
}
};