【问题标题】:Finding distinct numbers in queue using java使用java在队列中查找不同的数字
【发布时间】:2021-04-25 21:22:00
【问题描述】:

我想在队列中找到不同的数字,但除了数组等队列之外我不能使用任何东西。

这是我的代码:

    Queue distinct = new Queue(10);
    Queue distincttemp1 = new Queue(10);
    
    int count=0;
    Random rnd = new Random();
    boolean flag=true;
    for (int i = 0; i < 10; i++) {
        int x = rnd.nextInt(9);
        System.out.print(x + " ");
        distinct.enqueue(x);
    }
    System.out.println("");

除了将每个数字添加到队列中之外,我找不到找到重复多少数字的解决方案。它应该很简单,只需几个循环。你能帮我找到一个算法吗?

输入输出应该是这样的:

队列:4 8 5 8 4 3 2 8

输出:5

【问题讨论】:

    标签: java algorithm queue


    【解决方案1】:

    您可以使用 Queue 并使用 HashSet 跟踪不同的数字,因为集合不允许重复值。

            Queue<Integer> distinct = new LinkedList<>();
            Set<Integer> set = new HashSet();
            Random random = new Random();
            int number;
            for(int i=0; i<10; i++){
                number = random.nextInt(9);
                System.out.print(number+" ");
                distinct.add(number);
                set.add(number);
            }
            System.out.println("Distinct "+set.size());
    

    【讨论】:

      【解决方案2】:

      根据您的示例,您的号码介于08 之间。这意味着单个 Integer 变量足以标记您的任何数字的出现(我们只需要 9 位)。

      说明

      跟踪不同的值

      如果生成值x,则“标记”变量的二进制表示中的xth 位设置为1

      int marker = 0; 
      ...
              int x = random.nextInt(9);
              System.out.print(x + " ");
              marker |= (1 << x);
      ...
      

      不同值的数量

      然后,一旦循环完成,marker 中设置的位数对应于循环中生成的不同值的数量。

      ...
      System.out.println(Integer.bitCount(marker));  
      ...
      

      完整代码

          Random random = new Random();
          int marker = 0;
          for (int i = 0; i < 10; i++) {
              int x = random.nextInt(9);
              System.out.print(x + " ");
              marker |= (1 << x);
              queue.add(x);
          }
      
          System.out.println("\n" + Integer.bitCount(marker));
      

      4 7 1 4 0 1 4 0 7 8

      5

      【讨论】:

        猜你喜欢
        • 2016-07-12
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        • 2021-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多