题目:
输入样例:
5
1 3 2 4 5
输出样例:
3
1 4 5
分析:
先对数列排序,根据题意知排序主元左边的都比主元小,右边的都比主元大,那么排序时就相当于对主元左边和右边的数分别进行排序,主元位置不变,左边排序前是什么排序后还是什么,右边同理。且数列元素不重复,某位置元素改变则大小一定改变。
由上述可知,若排序前的某元素与排序后相同位置的元素大小相等则可能是主元,若同时该元素比它前边所有元素都大,则是主元,否则仍不是主元。
因为非主元元素排序前后位置也可能不变。
例如:3,2,1
排序后为:1,2,3
其中2的位置没变,但比前边的3小,不是主元。
看了网上的思路写的,代码如下(C/C++):
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int result[100000];
int main() {
int n, cnt = 0, max = 0;
scanf("%d", &n);
vector<int> lst1(n), lst2(n);
for (int i = 0; i < n; i++) {
scanf("%d", &lst1[i]);
lst2[i] = lst1[i];
}
sort(lst2.begin(), lst2.end());
for (int i = 0; i < n; i++) {
if (lst1[i] == lst2[i] && lst1[i] > max)
result[cnt++] = lst1[i];
if (lst1[i] > max)
max = lst1[i];
}
printf("%d\n", cnt);
for (int i = 0; i < cnt; i++) {
if (i == cnt - 1) printf("%d", result[i]);
else printf("%d ", result[i]);
}
printf("\n");
return 0;
}