search

Home  >  Q&A  >  body text

java - 现有1~100共一百个自然数,已随机放入一个有98个元素的数组a[98]。

要用JAVA实现
要求写出一个尽量简单的方案,找出没有被放入数组的那2个数,并在屏幕上打印这2个数。注意:程序不用实现自然数随机放入数组的过程。

PHPzPHPz2891 days ago619

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-18 09:08:33

    Someone gave an algorithm with a time complexity of O(n^2). I will give you an algorithm with a time complexity of O(n):

    public void printNum(int[] arr) {
        int[] result = new int[2];
        int[] heap = new int[101];
        for (int i = 0; i < 98; i++) {
            heap[arr[i]] = 1;
        }
        for (int i = 1; i <= 100; i++) {
            if (heap[i] != 1) {
                System.out.println(i);
            }
        }
    }

    reply
    0
  • 阿神

    阿神2017-04-18 09:08:33

    public int[] findNum(int[] arr) {
        int[] result = new int[2];
        var count = 0;
        for (int i = 1; i <= 100; i++) {
          if (count == 2) break;
          if (arr.indexOf(i) == -1) {
            result.push(i);
            count++;
          }
        }
        return result;
    }

    reply
    0
  • Cancelreply