给定一个整数数组,编写一个函数,找出索引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
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] subSort(int[] array) {
int[] sortedArr = Arrays.copyOf(array, array.length);
Arrays.sort(sortedArr);
Map<Integer, List<Integer>> indexMap = new HashMap<>();
for (int i = 0; i < sortedArr.length; i++) {
int value = sortedArr[i];
if (!indexMap.containsKey(value)) {
indexMap.put(value, new ArrayList<>());
}
indexMap.get(value).add(i);
}
int start = 0;
while (start < array.length) {
if (array[start] == sortedArr[start]) {
start++;
} else {
break;
}
}
if (start == array.length) {
int[] result = new int[2];
result[0] = -1;
result[1] = -1;
return result;
}
int end = array.length - 1;
while (end >= 0) {
if (array[end] == sortedArr[end]) {
end--;
} else {
break;
}
}
int[] result = new int[2];
result[0] = start;
result[1] = end;
return result;
}
}
//leetcode submit region end(Prohibit modification and deletion)