我必须在长度= 10的数组中找到丢失的整数(在0-9范围内随机生成)。我的想法是对数组进行排序,然后检查每个数组是否等于数组中的位置大批。我想出了以下代码:
public void nichtGetroffen(){
s.quickSort(enten, 0, enten.length -1);
sum = 0;
for (int i=0; i < enten.length; i++){
if(enten[i] != i){
System.out.print(i + "");
sum = sum +1;
}
}
问题是它有时有效,有时无效,不幸的是我不知道如何解决这个问题。 (enten是数组的名称)
最佳答案
如果对数组进行排序,如果下一个元素比当前元素大 1 以上,则说明缺少数字。然后,只需在数组的开头和结尾查找缺失的数字即可。
s.quickSort(enten, 0, enten.length -1);
// Print missing numbers less than the smallest element.
for (int j = 0; j < enten[0]; ++j) {
System.out.println(j);
}
// Print missing numbers between elements.
for (int i = 1; i < enten.length; ++i) {
// If enten[i - 1] + 1 >= enten[i], this loop body never runs.
for (int j = enten[i - 1] + 1; j < enten[i]; ++j) {
System.out.println(j);
}
}
// Print missing numbers greater than the largest element.
for (int j = enten[enten.length-1] + 1; j <= 9; ++j) {
System.out.println(j);
}
关于java - 查找有序数组中缺失的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39799944/