简体   繁体   中英

Use of queues in Java for an array of int, find two numbers that add up to specific sum n

I need to write a piece of code using Queues in Java that allows me to find, using 2 integers out of the given array that together give me a specific sum integer of x.

Let's say:

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

I understand what a queue is and the principal between enqueue and dequeue. I did the code without using queues with a double for loop but I don't really understand how to do it using queues.

Can anyone give me a hint or provide help? It would be very appreciated. (I'm also allowed to use stacks but queues seemed simpler to me).

Is it okay to sort the values, eg use a PriorityQueue ?

In that case, just use 2 PriorityQueue s, one sorted ascending, one sorted descending. peek() at both queues and add the values. If the sum is too low, poll() the first queue, if too high, poll() the second queue. Repeat until the sum is correct, or until the queues are empty.

Alternatively, use a single Deque , add the values after sorting, and work from both ends.

I tried to find a way to use only regular queues to work this out. So far, it will print all the possible pairs that add up to the specific sum you want. In this case I just put 5. However, an issue that came up is that I got duplicate pairs when iterating through the queue. It seems to be because of the while loop...I coded this in a hurry, but hopefully it gives you some hints and helped in some way!

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM