今天有一个业务上的问题,那就是在一串连续的数字中找出缺失的数字,我第一想到的就是借助hashmap去实现。如下:
int[] array = new int[]{1, 2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
Hashtable<Integer, Integer> hasht =
new Hashtable<Integer, Integer>();
for (int i = 0; i < array.length-1; i++) {
hasht.put(array[i], 1);
}
for (int i = 1; i <= array.length; i++) {
if (hasht.get(i) == null) {
System.out.println("缺失:" + i);
}
}
上述的方式是可以实现查询出想要的结果的。那么还有没有其他的办法实现呢?
int a[] = {1, 2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
int b[] = null;
b = new int[20];
for (int i = 0; i < a.length; i++) {
b[a[i] - 1] = 1;
}
for(int i = 0; i < b.length; i++) {
if (b[i] == 0) {
System.out.println("the lost number is " + (i + 1)