我有一个包含数字的数组,并且该数组未排序。用户可以从数组中删除数字。但用户应该能够稍后添加数字。
基本上我想在数据库中写入 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/