给定一个整数数组,编写一个函数,找出索引m和n,只要将索引区间[m,n]的元素排好序,整个数组就是有序的。注意:n-m尽量最小,也就是说,找出符合条件的最短序列。函数返回值为[m,n],若不存在这样的m和n(例如整个数组是有序的),请返回[-1,-1]。
思路:有序元素满足:>=左边元素最大值, <=右边元素最小值。
1)只要对数组进行两次遍历,分别记录左边元素(0~i-1)最大值high[i]和右边元素(i+1~n-1)最小值low[i]。
2)然后从前往后遍历找到左端点m,从后往前遍历找到右端点n。
3)若m<n,则找到,否则,不存在,返回[-1,-1]。
class Solution {
int low[1000000] = {0}, high[1000000] = {0}; // low[i]记录i+1~n之间的最小值,high[i]记录1~i-1之间的最大值
public:
vector<int> subSort(vector<int>& array) {
int n = array.size(); //有序元素满足:>=左边最大值, <=右边最小值
if (n==0) return {-1,-1};
int minx = array[n-1];
for (int i=n-1; i>=0; --i) 统计i右侧元素最小值
{
low[i] = minx;
minx = min(minx, array[i]);
}
int maxx = array[0];
for (int i=0; i<n; ++i) //统计右侧s元素最大值
{
high[i] = maxx;
maxx = max(maxx, array[i]);
}
int i = 0, j = n-1;
while (i<n) //找到左端点m
{
if (array[i]<=low[i]&&array[i]>=high[i])
i++;
else
break;
}
while (j>i) 找到右端点n
{
if (array[j]<=low[j]&&array[j]>=high[j])
j--;
else
break;
}
if (i<j) return {i,j};
return {-1,-1};
//return res;
}
};
题目链接:https://leetcode-cn.com/problems/sub-sort-lcci