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.
Idea 1. max(nums[0]... nums[i]) <= min(nums[i+1],..nums[n-1]), build maxArray from left, minArray from right
Time comlexity: T(n)
Space complexity: T(n)
using index:
1 class Solution { 2 public int partitionDisjoint(int[] A) { 3 int[] maxIndex = new int[A.length]; 4 for(int i = 1; i < A.length; ++i) { 5 if(A[i] > A[maxIndex[i-1]]) { 6 maxIndex[i] = i; 7 } 8 else { 9 maxIndex[i] = maxIndex[i-1]; 10 } 11 } 12 13 int[] minIndex = new int[A.length]; 14 minIndex[A.length-1] = A.length-1; 15 for(int i = A.length-2; i >= 0; --i) { 16 if(A[i] < A[minIndex[i+1]]) { 17 minIndex[i] = i; 18 } 19 else { 20 minIndex[i] = minIndex[i+1]; 21 } 22 } 23 24 for(int i = 0; i < A.length-1; ++i) { 25 if(A[maxIndex[i]] <= A[minIndex[i+1]]) { 26 return i + 1; 27 } 28 } 29 30 return 0; 31 } 32 }
No need to use index
扫描二维码关注公众号,回复:
5765958 查看本文章
1 class Solution { 2 public int partitionDisjoint(int[] A) { 3 int[] maxFromLeft = new int[A.length]; 4 maxFromLeft[0] = A[0]; 5 for(int i = 1; i < A.length; ++i) { 6 maxFromLeft[i] = Math.max(maxFromLeft[i-1], A[i]); 7 } 8 9 int[] minFromRight = new int[A.length]; 10 minFromRight[A.length-1] = A[A.length-1]; 11 for(int i = A.length-2; i >= 0; --i) { 12 minFromRight[i] = Math.min(minFromRight[i+1], A[i]); 13 } 14 15 for(int i = 0; i < A.length-1; ++i) { 16 if(maxFromLeft[i] <= minFromRight[i+1]) { 17 return i + 1; 18 } 19 } 20 21 return 0; 22 } 23 }