java - 获取数组中缺失的数字

标签 java arrays if-statement for-loop

我有一个包含数字的数组,并且该数组未排序。用户可以从数组中删除数字。但用户应该能够稍后添加数字。

基本上我想在数据库中写入 id。用户可以删除,但如果他添加一行,id 应该是已删除行中缺失的数字

目前我是这样解决的:

for (Object[] object : data) {
    if ((int) object[1] > id) {
        id = (int) object[1];
    }
}

但是这样我只能得到最大的数字,而不能得到缺失的数字。我怎样才能得到丢失的号码?

示例:

4, 2, 3, 1 the user deletes row 2 and row 4 so I have

3, 1 now I want to calculate or with if statements whatever to get the 2 and, if the user add a another row the, 4 back.

请记住,用户可以关闭程序,因此无法将号码保存在其他程序中数组!

  • 感谢您的帮助

最佳答案

根据您的示例,将从头到尾的数字相加,1+2+3+4 = 10,然后减去您的数字总和,1+2+4 = 7

所以 10 - 7 = 3(缺失的数字)

------------------------------------------------------------ - - -编辑 - - - - - - - - 这个怎么样?

public class SandBox7 {
public static void main(String[] args) {
    Integer[] array = new Integer[] { 1, 4, 9 };
    SandBox7 s = new SandBox7();
    List<Integer> mis = s.getMissingNumbers(array);
}

public List<Integer> getMissingNumbers(Integer[] in) {
    int max = getMaximum(in);
    // System.out.println(max);
    List<Integer> numbers = Arrays.asList(in);

    ArrayList<Integer> missing = new ArrayList<>();
    for (int i = 1; i < max; i++) {

        if (!numbers.contains(i)) {
            missing.add(i);
        }
    }
    return missing;
}

private int getMaximum(Integer[] in) {
    int tmp = -1;
    for (int i = 0; i < in.length; i++) {
        if (tmp < in[i])
            tmp = in[i];
    }
    return tmp;
}

}

关于java - 获取数组中缺失的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18379614/

相关文章:

ios - Swift 中的 JSON 复杂数组

javascript - 访问最后一个 if 语句条件结果值

php - if 语句的构建条件比较

java - Eclipse RCP : How to bring existing WorkbenchWindow to the top?

java - 使用 BigDecimalConverter 的 Primefaces 输入会忽略空字符串

php - 在php中的for循环中将元素推送到数组

java - 在 for 循环中添加到 HashMap 时跳过多个字符

java - 有没有其他方法可以预览 ANTLR 生成的解析树?

java - 如何在多模块 Maven 项目中配置 slf4j+logback?

c# - 在不使用 Split 函数的情况下将字符串转换为数组