描述
Given an array of integers A, find the smallest contiguous sub array B of A such that when you sort B in ascending order the whole array A becomes sorted as well.
For example if A = [1, 2, 3, 7, 4, 6, 5, 8] the smallest B will be [7, 4, 6, 5].
输入
The first line contains an integer N denoting the length of A. (1 <= N <= 100000)
The second line contains N integers denoting the array A. (0 <= Ai <= 100000000)
输出
The length of the smalltest sub array B.
样例输入
8
1 2 3 7 4 6 5 8
样例输出
4
题意:
给一个序列A,如果只要把A的子序列B进行排序的话,那么整个序列A就变得有序,求这个子序列B的最小长度是多少
思路:
直接把A数组copy一份,记作B,对B进行排序,然后从前往后找到第一个A,B第一个不想等的元素下标,再从后往前找到第一个A,B不想等的元素下标,然后这两个下标之间就是所求的B。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1e5+5;
int A[maxn];
int B[maxn];
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> A[i];
B[i] = A[i];
}
if (n == 1) {
cout << "1" << endl;
return 0;
}
sort(B,B+n);
int l,r;
for (int i = 0; i < n; ++i) {
if (A[i] != B[i]) {
l = i;
break;
}
}
for (int i = n-1; i >=0; --i)
if (A[i]!=B[i]) {
r = i;
break;
}
cout << r - l + 1 << endl;
return 0;
}