部分排序
1 題目地址
https://leetcode-cn.com/problems/sub-sort-lcci/
2 題目描述
給定一個整數數組,編寫一個函數,找出索引m和n,只要將索引區間[m,n]的元素排好序,整個數組就是有序的。注意:n-m儘量最小,也就是說,找出符合條件的最短序列。函數返回值爲[m,n],若不存在這樣的m和n(例如整個數組是有序的),請返回[-1,-1]。
示例:
輸入: [1,2,4,7,10,11,7,12,6,7,16,18,19]
輸出: [3,9]
提示:
0 <= len(array) <= 1000000
3 思路
1 從左向右是一個遞增序列,維護一個最大值,以及右索引,如果當前值大於最大值,
更新最大值,否則更新右索引。
2 從右向左維護一個遞減序列,維護一個最小值,以及左索引,如果當前值小於最小值,
更新最小值,以及左索引。
3 返回左索引、右索引。
public static int[] subSort(int[] array) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int leftIndex = -1;
int rightIndex = -1;
for (int i = 0; i < array.length; i++) {
//左->右
if (array[i] >= max) {
max = array[i];
} else {
rightIndex = i;
}
//右->左
int temp = array.length - i - 1;
if (array[temp] <= min) {
min = array[temp];
} else {
leftIndex = temp;
}
}
return new int[]{leftIndex, rightIndex};
}