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 (≤10^5). Then the next line contains N distinct positive integers no larger than 10^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
思路
- 定义两个数组 leftMax[maxn] 和 leftMax[maxn],leftMax[maxn] 用于记录序列中每一位左边的最大值,leftMax[maxn] 用于记录序列中每一位右边的最小值。如果 nums[i] 大于左边的最大值 leftMax[i] 且小于右边的最小值 rightMin[i],那么 nums[i] 一定可以作为主元。
- 其中,leftMax[0] 应设为0,这样就假设了 nums[0] 左边没有比它大的元素;rightMin[n - 1] 应设为最大值 1 « 31 - 1,这样就假设了 nums[n - 1] 右边没有比它小的元素。这样在给这两个数组赋值的过程中,相当于把初始最大值设为了 nums[0] 即 0,把初始最小值设为了 nums[n - 1] 即 1 « 31 - 1。同时在判断主元时方便了边界元素的判断,
注意点
- 直接暴力判断的做法会超时
- 当主元个数为0时,第二行虽然没有输出主元,但必须输出一个换行(否则会有一个点格式错误…)
#include <cstdio>
#include <vector>
using namespace std;
const int maxn = 100000;
int main() {
int n, nums[maxn], leftMax[maxn], rightMin[maxn];
scanf("%d", &n);
leftMax[0] = 0;
rightMin[n - 1] = 1 << 31 - 1;
for (int i = 0; i < n; i++) {
scanf("%d", &nums[i]);
if (i != n - 1) {
if (nums[i] > leftMax[i]) {
leftMax[i + 1] = nums[i];
} else {
leftMax[i + 1] = leftMax[i];
}
}
}
for (int i = n - 1; i >= 1; i--) {
if (nums[i] < rightMin[i]) {
rightMin[i - 1] = nums[i];
} else {
rightMin[i - 1] = rightMin[i];
}
}
vector<int> ans;
for (int i = 0; i < n; i++) {
if (nums[i] > leftMax[i] && nums[i] < rightMin[i]) {
ans.push_back(nums[i]);
}
}
printf("%d\n", ans.size());
for (int i = 0; i < ans.size(); i++) {
printf("%d", ans[i]);
if (i != ans.size() - 1) {
printf(" ");
}
}
printf("\n");
return 0;
}