我必须在长度= 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);
}

10-06 11:23