要用JAVA实现
要求写出一个尽量简单的方案,找出没有被放入数组的那2个数,并在屏幕上打印这2个数。注意:程序不用实现自然数随机放入数组的过程。
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);
}
}
}
阿神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;
}