gpt4 book ai didi

java - 如何使用java查找给定序列数组列表中的缺失元素?

转载 作者:行者123 更新时间:2023-12-02 03:40:24 25 4
gpt4 key购买 nike

1.我有一个带有起始元素和数组列表限制的整数数组列表。示例 [5,6,9,10]

2.我必须迭代并找到丢失的元素及其位置。 根据上面的例子,我的输出应该是数字7(位置3),数字8(位置4)丢失了。

3.现在我正在打印所有数字,而不是获取丢失的元素。

下面是代码:

 public static List<Integer> issue_ret=new ArrayList<>();
Iterator<Integer> iter = issue_ret.iterator();
while(iter.hasNext()){
int value = iter.next();
if("1".equals(value)){
iter.remove();
}
else{
System.out.println("Missing value:"+value);
}
}

谁能帮我解决这个问题吗?

最佳答案

建议您一种比 ArrayList.contains() 更有效但更有限的方法:

    ArrayList<Integer> list = new ArrayList<>(Arrays.asList(new Integer[]{5, 6, 9, 10}));

int head = list.get(0);
int tail = list.get(list.size() - 1);

int length = tail - head + 1;
int[] array = new int[length];

for (int i : list) {
array[i - head] = 1;
}

for (int i = 0; i < array.length; i++) {
if (array[i] == 0) {
System.out.println(String.format("Missing %d, position %d", i + head, i + 1));
}
}

限制是:最上面的Integer数字不能太大。无论如何,这是一种以空间换时间的方式,是否使用取决于你的实际需要。

关于java - 如何使用java查找给定序列数组列表中的缺失元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36905571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com