给定一组连续的整数,例如:10,11,12,……,20,但其中缺失一个数字,试找出缺失的数字
1 import java.util.*;2
3 public classMain {4 public static voidmain(String[] args) {5 //构造从start到end的序列:
6 final int start = 10;7 final int end = 20;8 List list = new ArrayList<>();9 for (int i = start; i <= end; i++) {10 list.add(i);11 }12 //随机删除List中的一个元素:
13 int removed = list.remove((int) (Math.random() *list.size()));14 int found =findMissingNumber(start, end, list);15 System.out.println(list.toString());16 System.out.println("missing number: " +found);17 System.out.println(removed == found ? "测试成功" : "测试失败");18 }
//以下为算法的核心方法19 static int findMissingNumber(int start, int end, Listlist) {20 int found = 0;21 for(int i = start; i< end; i++){22 if(list.get(i-10) !=i){23 found =i;24 break;25 }26 }27 returnfound;28 }29 }
2. 还可以用求合法,两个数组分别求和,再相减,得出的就是缺少的数,很简单。代码如下:
static int findMissingNumber(int start, int end, List list) {
//求合法
int sum1 = 0;
int sum2 = 0;
for(int i = start; i<= end;i++){
sum1 +=i;
}
for(Integer in : list){
sum2 += in;
}
System.out.println(sum1-sum2);
return Math.abs(sum1-sum2);
}
3.最简单的方法:用list.contains();方法判断
static int findMissingNumber(int start, int end, List list) {
int missNum = 0;
for(int i = start; i<= end; i++){
if( ! list.contains(i) ){
missNum = i;
}
}
return missNum;
}