There is a classical process named partition in the famous quick sort algorithm. In this process we typically choose one element as the pivot. Then the elements less than the pivot are moved to its left and those larger than the pivot to its right. Given N distinct positive integers after a run of partition, could you tell how many elements could be the selected pivot for this partition?
For example, given N=5 and the numbers 1, 3, 2, 4, and 5. We have:
- 1 could be the pivot since there is no element to its left and all the elements to its right are larger than it;
- 3 must not be the pivot since although all the elements to its left are smaller, the number 2 to its right is less than it as well;
- 2 must not be the pivot since although all the elements to its right are larger, the number 3 to its left is larger than it as well;
- and for the similar reason, 4 and 5 could also be the pivot.
Hence in total there are 3 pivot candidates.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤105 ). Then the next line contains N distinct positive integers no larger than 109
. The numbers in a line are separated by spaces.
Output Specification:
For each test case, output in the first line the number of pivot candidates. Then in the next line print these candidates in increasing order. There must be exactly 1 space between two adjacent numbers, and no extra space at the end of each line.
Sample Input:
5
1 3 2 4 5
Sample Output:
3
1 4 5
思路
题目大意是找出序列中的主元,主元要求左边的数都比它小,右边的数都比它大。第一时间想到嵌套for循环,不过很快pass了,因为n2复杂度实在是高。然后想到两个数组,left_max和right_min。left_max用来记录一个数左边最大的数,而right_min用来记录其右边最小的数,如果左边最大的数比它小且右边最小的数比它大则该数就是主元。这应该算是一种用空间换时间的做法
tip:如果没有主元,输出0之后再输出两个回车,不然测试点2是格式错误。
#include <iostream>
#include <cstdlib>
#include <vector>
#include <climits>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> vec;
vector<int> left_max;
int nmax = -1;
for (int i = 0; i < n; i++)
{
//读入数据的同时记录这个数左边最大的数
int num;
cin >> num;
vec.push_back(num);
if (num > nmax)
{
left_max.push_back(nmax);
nmax = num;
}
else
left_max.push_back(nmax);
}
vector<int> right_min(n);
int nmin = INT_MAX;
//再从尾到头遍历一遍求每个数右边最小的数
for (int i = n - 1; i >= 0; i--)
{
if (vec[i] < nmin)
{
right_min[i] = nmin;
nmin = vec[i];
}
else
right_min[i] = nmin;
}
vector<int> ans;
for (int i = 0; i < n; i++)
if (left_max[i] < vec[i] && right_min[i] > vec[i])
ans.push_back(vec[i]);
if (ans.size() == 0)
{
//输出两个回车
cout << '0' << endl << endl;
return 0;
}
cout << ans.size() << endl;
for (int i = 0; i < ans.size(); i++)
{
if (i != 0)
cout << ' ';
cout << ans[i];
}
system("pause");
return 0;
}