【问题标题】:Use of queues in Java for an array of int, find two numbers that add up to specific sum n在 Java 中将队列用于 int 数组,找到两个加起来为特定总和 n 的数字
【发布时间】:2016-01-16 11:05:18
【问题描述】:

我需要使用 Java 中的 Queues 编写一段代码,它允许我使用给定数组中的 2 个整数来查找,它们一起给我一个特定的和整数 x。

假设:

int[] array = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 5;

我了解队列是什么以及入队和出队之间的原则。我在没有使用带有双 for 循环的队列的情况下编写了代码,但我真的不明白如何使用队列。

谁能给我提示或提供帮助?将不胜感激。 (我也可以使用堆栈,但队列对我来说似乎更简单)。

【问题讨论】:

  • 数组总是排序的吗?
  • 不,随机数未排序。我只是把它整理出来,以便快速输入随机的东西。道歉。

标签: java arrays stack queue


【解决方案1】:

是否可以对值进行排序,例如使用PriorityQueue?

在这种情况下,只需使用 2 个PriorityQueues,一个升序排序,一个降序排序。 peek() 在两个队列中并添加值。如果总和太低,poll() 第一个队列,如果太高,poll() 第二个队列。重复直到总和正确,或者直到队列为空。

或者,使用单个Deque,在排序后添加值,并从两端工作。

【讨论】:

    【解决方案2】:

    我试图找到一种仅使用常规队列来解决此问题的方法。到目前为止,它将打印所有可能的对,这些对加起来等于您想要的特定总和。在这种情况下,我只放了 5。但是,出现的一个问题是我在遍历队列时得到了重复的对。这似乎是因为 while 循环......我匆忙编写了这个代码,但希望它能给你一些提示并在某种程度上有所帮助!

    import java.util.Queue;
    import java.util.LinkedList;
    
    public class QueueSums {
    
    public static void main(String args[]) {
        int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        Queue<Integer> queue = new LinkedList<>();
    
        for (int i : array) {
            queue.add(i);
        }
    
        System.out.println(queue);
    
        while (iterateQueue(queue) == false) {
            queue.poll();
            iterateQueue(queue);
        }
    
    }
    
    public static boolean iterateQueue(Queue<Integer> queue) {
        Queue<Integer> queueCopy = new LinkedList<>();
        queueCopy.addAll(queue);
    
        int sum = 5;
        System.out.println(sum);
    
        int num1 = queueCopy.peek();
    
        while (queueCopy.size() > 0) {
            int num2 = queueCopy.peek();
    
            if (sum == num1 + num2) {
                System.out.println(num1 + " + " + num2 + " works");
                return true;
            }
    
            else {
                queueCopy.poll();
            }
        }
        return false;
    
    }
    

    【讨论】:

    • 哈哈谢谢,我忘了回复,但我自己想通了。我将运算符堆叠在一堆字符串中,将数字堆叠在一堆整数中,然后系统地对它们进行 pop()。
    猜你喜欢
    • 1970-01-01
    • 2017-06-06
    • 2020-06-06
    • 2021-06-14
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多