问题描述
给定一个数组 A ,将其划分为两个不相交(没有公共元素)的连续子数组 left 和 right , 使得:
left 中的每个元素都小于或等于 right 中的每个元素。
left 和 right 都是非空的。
left 要尽可能小。
在完成这样的分组后返回 left 的 长度 。可以保证存在这样的划分方法。
示例 1:
输入:[5,0,3,8,6]
输出:3
解释:left = [5,0,3],right = [8,6]
示例 2:
输入:[1,1,1,0,6,12]
输出:4
解释:left = [1,1,1,0],right = [6,12]
提示:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
可以保证至少有一种方法能够按题目所描述的那样对 A 进行划分。
解法一:
先正向扫描一遍数组,找到左区间的最小值
,然后在从后向前扫描数组,找到右区间的最小值
,最后综合得到的左区间的最大
和右区间的最小
得出答案。时间复杂度O(n),空间复杂度O(n)
public static List<List<Integer>> smallestRangeI1I(int[] A) {
if (null == A || A.length == 0) {
return Collections.emptyList();
}
int[][] tmp = new int[2][A.length];
for (int i = 0; i < A.length; i++) {
tmp[0][i] = i == 0 || A[i] > tmp[0][i - 1] ? A[i] : tmp[0][i - 1];
tmp[1][A.length - 1 - i] = i == 0 || A[A.length - 1 - i] < tmp[1][A.length - i] ? A[A.length - 1 - i] : tmp[1][A.length - i];
}
List<Integer> left = new ArrayList<Integer>();
List<Integer> right = new ArrayList<Integer>();
int index = 0;
while (index < A.length - 1) {
left.add(A[index]);
if (tmp[0][index] < tmp[1][index + 1]) {
break;
}
index++;
}
index++;
while (index < A.length) {
right.add(A[index]);
index++;
}
List<List<Integer>> result = new ArrayList<List<Integer>>();
result.add(left);
result.add(right);
return result;
}
解法二
public static List<List<Integer>> partitionDisjoint1(int[] A) {
int rightMax = A[0];
int leftMax = A[0];
int index = 0;
for (int i = 0; i < A.length; i++) {
rightMax = Math.max(rightMax, A[i]);
if (A[i] < leftMax) {
leftMax = rightMax;
index = i;
}
}
List<Integer> left = new ArrayList<Integer>();
for(int i = 0; i<=index; i++){
left.add(A[i]);
}
List<Integer> right = new ArrayList<Integer>();
for(int i = index + 1; i < A.length; i ++){
right.add(A[i]);
}
List<List<Integer>> result = new ArrayList<List<Integer>>();
result.add(left);
result.add(right);
return result;
}