PAT 1144 java

1.题意

给出N个整数的序列,你需要找出序列中未出现的最小正整数。

2.分析

  • 使用数组存储未被找到过的数字
  • 使用Set粗出未被找到过的数字

3.测试用例

10
5 -25 9 6 1 3 4 2 5 17

10
5 7 9 6 1 3 4 2 8 10

4.代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        Reader.init(System.in);
        int n = Reader.nextInt();
        int i ;
        int array[] = new int[n+2];

        int number ;
        for(i = 0;i< n;i++) {
            number = Reader.nextInt();
            if (number > 0) {
                if (number > n) {
                    continue;
                } else {
                    array[number] = number;
                }
            }
        }
        for(i = 1;i<= n+1;i++) {
            if (array[i] == 0) {
                System.out.println(i);
                break;
            }
        }
    }
}

class Reader {
    static BufferedReader reader;
    static StringTokenizer tokenizer;

    /** call this method to initialize reader for InputStream */
    static void init(InputStream input) throws IOException {
        reader = new BufferedReader(new InputStreamReader(input) );
        tokenizer = new StringTokenizer("");
    }

    /** get next word */
    static String next() throws IOException {
        while ( ! tokenizer.hasMoreTokens() ) {//如果后面还有数据,则直接返回
            //TODO add check for eof if necessary
            tokenizer = new StringTokenizer(reader.readLine() );//否则,读取下一行
        }
        return tokenizer.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt( next() );
    }

    static double nextDouble() throws IOException {
        return Double.parseDouble( next() );
    }

    //获取字符 => 因为 next()方法返回的是一个String
    static char nextChar() throws IOException {
        return next().charAt(0);
    }
}

5.执行结果

PAT 1144 java 版

6.优化过程

  • 虽然所有的数字范围都是int类。但是最大的整数并不可能是(2^31-1),因为最多会输入一个10^5个数,所以最小的数的取值范围就是[1,10^5+1]。根据这个思路,优化if的边界处理值。
  • 使用Set之后,发现使用for循环输出第一位,竟然要比使用 iterator 的性能要好
for (Integer integer : result) {
            System.out.println(integer);
            break;
}

使用上面的代码时,超时样例只有三个,但是如果使用System.out.println(result.iterator().next());,则有四个超时样例。

相关文章:

  • 2021-05-26
  • 2021-09-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-18
猜你喜欢
  • 2021-12-14
  • 2021-04-15
  • 2021-07-02
  • 2021-11-05
  • 2022-12-23
  • 2022-12-23
  • 2022-01-19
相关资源
相似解决方案