1. 程式人生 > >915. Partition Array into Disjoint Intervals(O(n)暴力)

915. Partition Array into Disjoint Intervals(O(n)暴力)

915. Partition Array into Disjoint Intervals

My SubmissionsBack to Contest

  • 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 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.

 

思路:開始再想用二分來解決,後來發現沒必要,並且二分的思路是錯的。

          發現只有正反掃描一遍就行了。

 

程式碼:

#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;
           }
       }
    }
    

};