gpt4 book ai didi

java - 在数字数组中查找缺失数字的最快方法

转载 作者:IT老高 更新时间:2023-10-28 13:51:46 26 4
gpt4 key购买 nike

我有一个从 1 到 100(包括两者)的数字数组。数组的大小为 100。数字是随机添加到数组中的,但数组中有一个随机的空槽。找到该插槽以及应该放入插槽的数字的最快方法是什么?最好使用 Java 解决方案。

最佳答案

你可以在 O(n) 中做到这一点。遍历数组并计算所有数字的总和。现在,从 1 到 N 的自然数之和可以表示为 Nx(N+1)/2。在您的情况下,N=100。

Nx(N+1)/2 中减去数组的总和,其中 N=100。

那是缺少的数字。在计算总和的迭代过程中可以检测到空槽。

// will be the sum of the numbers in the array.
int sum = 0;
int idx = -1;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == 0)
{
idx = i;
}
else
{
sum += arr[i];
}
}

// the total sum of numbers between 1 and arr.length.
int total = (arr.length + 1) * arr.length / 2;

System.out.println("missing number is: " + (total - sum) + " at index " + idx);

关于java - 在数字数组中查找缺失数字的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2113795/

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