【PAT】A1101 Quick Sort

【PAT】A1101 Quick Sort

@(PAT)

链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805366343188480

思路:
1. 题目意思是找到数列中,左边的元素都比之小,右边的元素都比之大的元素。
2. 该题目高效思路与A1093的基本相同,my blog:https://blog.csdn.net/timso1997/article/details/80503929
3. 用两个数组存储每个位置左边最大的数和右边最小的数,然后根据该两个数据比较,这里高效的思想是如果遍历到的数比当前左边最大数大的话,该位置的左边最大数就为该数,并更新当前左边最大数;否则就为上一个位置的左边最大数,同理可得右边最大数。
4. 注意的是,0位置的左边最大数设置为0,最后一个位置的右边最小数设置为INF。
5. 测试样例中,有一个点是没有找到满足题意的数,但此时仍然要输出换行,因此提示格式错误。

My AC code:

#define _CRT_SECURE_NO_DEPRECATE

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>

#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>

using namespace std;

#define N 100001
#define INF 10000000001

int nums[N];

int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &nums[i]);
    }
    vector<int> lmax(n);
    vector<int> rmin(n);
    int max = -1;
    for (int i = 0; i <= n- 2; i++) {
        if (nums[i] > max) {
            lmax[i+ 1] = nums[i];
            max = nums[i];
        }
        else {
            lmax[i + 1] = lmax[i];
        }
    }
    /*for (int i = 0; i < lmax.size(); i++) {
        cout << lmax[i] << endl;
    }*/
    int min = INF;
    rmin[n - 1] = INF;
    for (int i = n - 1; i >= 1; i--) {
        if (nums[i] < min) {
            rmin[i - 1] = nums[i];
            min = nums[i];
        }
        else {
            rmin[i - 1] = rmin[i];
        }
    }
    /*for (int i = 0; i < rmin.size(); i++) {
        cout << rmin[i] << endl;
    }*/
    vector<int> res;
    for (int i = 0; i < n; i++) {
        if (nums[i] > lmax[i] && nums[i] < rmin[i]) {
            res.push_back(nums[i]);
        }
    }
    printf("%d\n", res.size());
    for (int i = 0; i < res.size(); i++) {
        if (i == 0) {
            printf("%d", res[i]);
        }
        else {
            printf(" %d", res[i]);
        }
    }
    if (res.size() == 0) {
        printf("\n");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值