gpt4 book ai didi

java - 使用随机生成器查找数组中缺失的数字

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

我正在尝试使随机生成器不会在数组中产生相同的数字。我也不知道如何找到丢失的号码。我尝试了 if 语句,它有效,但它重复。

问题问题“查找数组中缺失的数字。该数组由 1 到 10 之间的数字随机组成。数组中的一个数字缺失,您必须找到它。使用一个循环。示例 { 5,6,9,4,1,2,8,3,10} – 结果将是:7

import java.util.Random;


public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [10];
Random rand = new Random();
int numArr = 1;

for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;

if (numbers[i] == numArr)
numArr++;
else
System.out.println("The missing num is " +numArr);
}

for(int val : numbers)
{
System.out.println("The next value is " +
val);
}
}
}

最佳答案

假设:

  • 数字是唯一的
  • 仅缺少一项
  • 数字范围为 [1, 10](含)。

解决方案

return 55 - Arrays.stream(yourArr).sum();

运行时间复杂度为 O(n),空间复杂度为 O(1)。

如果我们打破假设。

您将需要 O(N) 空间来找出丢失的条目。要保存标记,您可以使用 ListBitSet 或 2 个字节并手动管理它。这里的N是随机数生成宽度。

关于java - 使用随机生成器查找数组中缺失的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46855327/

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