# 题目描述

题目链接

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 (≤10510^5). Then the next line contains N distinct positive integers no larger than 10910^9. 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

# 解释

第一行给定序列中数字的个数,第二行给出这个序列,各个数字不重复。当一个数大于左侧所有数、小于右侧所有数时,这个数为 pivot。要求输出 pivot 的个数并升序输出。

# 一种思路

可以创建三个数组,分别保存第 i 个位置及其左侧最大的数、第 i 个位置及其右侧最小的数、第 i 个位置的数。那么只需 O (n) 的时间复杂度就可以找出 pivot。把它加到 set 里自动就排好序了。

这里要注意第二个测试点没有 pivot,但是输出 0 以后仍要单独输出一个空行。

# 解答

#include <bits/stdc++.h>
using namespace std;
const int MAX = 100005;
int leftMAX[MAX], rightMIN[MAX], num[MAX];
int N;
int main()
{
    cin >> N;
    for (int i = 0; i < N; i++){
        cin >> num[i];
        if (i == 0){
            leftMAX[0] = num[0];
        } else {
            leftMAX[i] = num[i] > leftMAX[i - 1] ? num[i] : leftMAX[i - 1];
        }
    }
    for (int i = N - 1; i >= 0; i--){
        if (i == N-1){
            rightMIN[i] = num[i];
        } else {
            rightMIN[i] = num[i] < rightMIN[i + 1] ? num[i] : rightMIN[i + 1];
        }
    }
    set<int> res;
    for (int i = 0; i < N; i++)
    {
        if (num[i] >= leftMAX[i] && num[i] <= rightMIN[i]){
            res.insert(num[i]);
        }
    }
    cout << res.size() << endl;
    bool space = false;
    for (auto i : res)
    {
        if (space){
            cout << " ";
        }
        cout << i;
        space = true;
    }
}
更新于 阅读次数

请我喝[茶]~( ̄▽ ̄)~*

c01dkit 微信支付

微信支付

c01dkit 支付宝

支付宝

c01dkit qqpay

qqpay