'Priority Queue of an array of integers in java
I want to compare by the second element of the array [[0, 30],[5, 10],[15, 20]].
PriorityQueue<int[]> heap = new PriorityQueue(intervals.length, (a, b) -> a[1] - b[1]);
But I am getting an error as below
Line 8: error: array required, but Object found PriorityQueue<Integer[]> heap = new PriorityQueue(intervals.length, (a, b) -> a[1] - b[1]); ^ Line 8: error: array required, but Object found PriorityQueue<Integer[]> heap = new PriorityQueue(intervals.length, (a, b) -> a[1] - b[1]);
^ 2 errors
Solution 1:[1]
You could use Integer.compare
PriorityQueue<int[]> heap = new PriorityQueue<>(intervals.length, (a,b) -> Integer.compare(a[1],b[1]));
Solution 2:[2]
Well, in your example, you have a 2D array; however, in your code snippet, you're assuming that a single-dimensional array should be kept in the Queue. So, which is your question? are you sure you want to maintain the Queue of 2D arrays? that doesn't mean, that you would have a Queue of pairs/tuples, that means, that each element in that queue, will be a discrete 2D array object. And in this case, probably each array will have more than one element.. and that means, that you should most likely iterate through them.. but if you're sure what you want with this code to be achieved and it's correct, then you can compare first elements like this:
PriorityQueue<int[][]> heap = new PriorityQueue<int[][]>((a, b) -> {
if (a[0][0] > b[0][0]) {
return 1; //change according to your logic
} else if (a[0][0] < b[0][0]) {
return -1; //change according to your logic
} else {
return 0; //change according to your logic
}
});
Solution 3:[3]
You can use:
PriorityQueue<int[]> pq = new PriorityQueue<>(intervals.length,
Comparator.comparingInt(interval -> interval[1]));
Solution 4:[4]
Just add "<>" after PriorityQueue:
PriorityQueue<int[]> heap = new PriorityQueue<>(intervals.length, (a, b) -> a[1] - b[1]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Happy Coder |
| Solution 2 | |
| Solution 3 | Deepthi V V |
| Solution 4 | user3625985 |
