题目描述
著名的快速排序算法里有一个经典的划分过程:通常采用某种方法取一个元素作为主元,通过交换,把比主元小的元素放到它的左边,比主元大的元素放到它的右边。
给定一个划分后的正整数序列,请问有多少个元素可能是划分过程中选取的主元? 并按升序输出这些主元。
解答要求时间限制:1000ms, 内存限制:256MB
输入
第 1 行一个正整数 N,表示正整数序列的长度,取值范围 [1, 10^5]
第 2 行 N 个互不不同的正整数,每个数的取值范围[1, 10^9]
输出
按升序排列的可能主元的列表,以单个空格分隔;或者空列表。
样例
输入样例 1
5 1 3 2 4 5
输出样例 1
[1 4 5]
提示样例 1
- 1 的左边没有元素,右边的元素都比它大,所以它可能是主元。
- 尽管 3 的左边元素都比它小,但其右边的 2 比它小,所以它不能是主元; 尽管 2 的右边元素都比它大,但其左边的 3 比它大,所以它不能是主元。
- 同理,4 和 5 都可能是主元。
因此,1、4、5 是可能的主元,按升序输出为 [1 4 5] 。
解题代码
#include <iostream>
#include <locale>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
// 待实现函数,在此函数中填入答题代码;
vector<int> QuickSort(const vector<int>& numbers)
{
vector<int> result;
//记录左边最大值
int preMax = 0;
for (int num : numbers) {
//若当前数比栈内最后一个数小,那么栈内最后一个数不是主元,出栈
//且对于当前数,存在左边比它大的数,当前数也不是主元,无需入栈
while (!result.empty() && num <= result.back()) {
preMax = max(result.back(), preMax);
result.pop_back();
}
//若左边没有比它大的数,则入栈
if (num > preMax) {
result.push_back(num);
}
}
return result;
}
};
inline int ReadInt()
{
int number;
cin >> number;
return number;
}
template<typename T>
inline vector<T> ReadVector(int size)
{
vector<T> objects(size);
for (int i = 0; i < size; ++i) {
cin >> objects[i];
}
return objects;
}
template <typename T> inline void WriteVector(const vector<T> &objects, char delimeter = ' ')
{
auto it = objects.begin();
if (it == objects.end()) {
return;
}
cout << *it;
for (++it; it != objects.end(); ++it) {
cout << delimeter << *it;
}
}
int main()
{
int numbersNum = ReadInt();
vector<int> numbers = ReadVector<int>(numbersNum);
Solution solu;
auto res = solu.QuickSort(numbers);
cout << "[";
WriteVector(res, ' ');
cout << "]" << endl;
return 0;
}