915. Partition Array into Disjoint Intervals
- User Accepted:1501
- User Tried:1874
- Total Accepted:1525
- Total Submissions:4281
- Difficulty:Medium
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.
思路:开始再想用二分来解决,后来发现没必要,并且二分的思路是错的。
发现只有正反扫描一遍就行了。
代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int partitionDisjoint(vector<int>& A) {
int cnt[30005];
memset(cnt,127,sizeof(cnt));
int n = A.size();
cnt[n-1] =A[n-1];
for(int i=n-2;i>=1;i--)
{
cnt[i] =min(cnt[i+1],A[i]);
}
int M=0;
for(int i=0;i<n;i++)
{
M=max(M,A[i]);
if(M<=cnt[i+1])
{
return i+1;
}
}
}
};