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

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

噜噜哒
浏览 567回答 2
2回答

ABOUTYOU

有人给出了一个时间复杂度O(n^2)的算法,我给一个O(n)的算法把:public void printNum(int[] arr) {&nbsp; &nbsp; int[] result = new int[2];&nbsp; &nbsp; int[] heap = new int[101];&nbsp; &nbsp; for (int i = 0; i < 98; i++) {&nbsp; &nbsp; &nbsp; &nbsp; heap[arr[i]] = 1;&nbsp; &nbsp; }&nbsp; &nbsp; for (int i = 1; i <= 100; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (heap[i] != 1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(i);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

蝴蝶不菲

public int[] findNum(int[] arr) {&nbsp; &nbsp; int[] result = new int[2];&nbsp; &nbsp; var count = 0;&nbsp; &nbsp; for (int i = 1; i <= 100; i++) {&nbsp; &nbsp; &nbsp; if (count == 2) break;&nbsp; &nbsp; &nbsp; if (arr.indexOf(i) == -1) {&nbsp; &nbsp; &nbsp; &nbsp; result.push(i);&nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return result;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java