【PAT】A1080. Sort with Swap(0,*)(贪心算法,超时处理)

【PAT】A1080. Sort with Swap(0,*)(贪心算法,时间)

@(PAT)

链接:https://www.patest.cn/contests/pat-a-practise/1067

思路:
每次只准将数列的0和一个数交换,求交换的最少次数。
需要注意的地方:
1. 存数数据的方式,一开始使用的是直接一个vector直接把数组存起来,这样的话会导致遍历超时。这里使用的方法是按照index用vector把每个数字所在的位置存储起来,类似map,这样就能够利用所给的数是0-N这个条件,避免超时。
2. 一开始有2个点没过,原因是当0在位置0的时候,寻找与0交换的位置每次都从1开始找,导致超时。正确的做法是:每次从上次结束的地方开始找,因为之前找的已经被排序正确了。

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;

int main() {
    int n;
    scanf("%d", &n);
    vector<int> nums(n);
    for (int i = 0; i < n; i++) {
        int temp;
        scanf("%d", &temp);
        nums[temp] = i;
    }
    int count = 0;
    int i = 1;
    while (1) {
        if (nums[0] == 0) {
            while (i < n) {
                if (nums[i] != i) {
                    break;
                }
                i++;
            }
            if (i== n) {
                printf("%d", count);
                return 0;
            }
            nums[0] = nums[i];
            nums[i] = 0;
            count++;
        }
        // or while
        if (nums[0] != 0) {
            int t = nums[0];
            nums[0] = nums[t];
            nums[t] = t;
            count++;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苦茶子12138

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值