文章

37

粉丝

0

获赞

7

访问

3.4k

头像
【2018年】408计算机统考真题模拟考试 - 第41题答案笔记
数据结构
发布于2025年5月18日 20:26
阅读数 65

计算机考研408统考历年真题及答案解析

(1) 由于目标是在时间上尽可能高效,不用特别考虑空间复杂度的高低,因此可以先遍历数组取最大值max,再创建一个长度为max+1的数组count用于记录每个正整数出现的次数,再遍历一遍数组,当遇到正整数i时,令count[i]+1。遍历完毕后再遍历一遍(从1开始)count数组,找到第一个count值为0的索引并返回。若上次遍历没能成功返回,则最小正整数必然为max+1。

(2) C语言代码如下:

#include <stdio.h>
#include <stdlib.h>

int solution(int arr[], int n) {
    int max = 0;

    for (int i = 0; i < n; i++) {
        if (arr[i] > max) max = arr[i];   
    }

    if (max == 0) return 1;    // 如果数组内没有正整数,那么max只会为0,此时可以直接返回1

    int count[max + 1];    // 记录数组arr中每个正整数出现的次数

    for (int i = 0; i < n; i++) {

        if (arr[i] > 0) count[arr[i]]++;    // 当遇到正整数i时,令count[i]+1

    }

    for (int i = 1; i <= max; i++) {
        if (count[i] == 0) return i;    // 遍历一遍(从1开始)count数组,找到第一个count值为0的索引并返回
 ...

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发