public static int smallestMissingPositive(int[] A) {
    int n = A.length;
    boolean[] present = new boolean[n + 1];

    // 将A中出现过的正整数在present数组中标记为true
    for (int i = 0; i < n; i++) {
        if (A[i] > 0 && A[i] <= n) {
            present[A[i]] = true;
        }
    }

    // 在present数组中查找第一个未被标记的正整数,即为最小未出现正整数
    for (int i = 1; i <= n; i++) {
        if (!present[i]) {
            return i;
        }
    }

    // 如果所有正整数都出现过,则返回n+1
    return n + 1;
}

解析:

  1. 定义一个boolean类型的数组present,长度为n+1,用于标记1~n中的正整数是否在A中出现过;
  2. 遍历数组A,如果A[i]是正整数且在1~n范围内,则将present[A[i]]标记为true;
  3. 在present数组中查找第一个未被标记的正整数,即为最小未出现正整数;
  4. 如果所有正整数都出现过,则返回n+1。
用java代码实现给定一个包含 N 个整数的数组 A返回 A 中没有出现的最小正整数

原文地址: https://www.cveoy.top/t/topic/bkLN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录