英文:
How to sort with PriorityQueue<int[]> 3-values in Java?
问题
我正尝试使用 `PriorityQueue` 和 `Comparator` 进行排序,但我不知道如何编写方法。
如果第三个元素相同,则我希望将其与第一个元素进行比较。如果第一个元素也相同,则我希望将其与第二个元素进行比较。
我尝试在比较方法中编写如下:
```java
if (o1[2] < o2[2])
return 1;
else if (o1[2] > o2[2])
return -1;
return 0;
但不起作用... 请帮帮我...
Queue<int[]> q = new PriorityQueue<int[]>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[2] == o2[2]) {
if (o1[0] == o2[0]) {
return Integer.compare(o1[1], o2[1]);
} else {
return Integer.compare(o1[0], o2[0]);
}
} else {
return Integer.compare(o2[2], o1[2]);
}
}
});
q.add(new int[] {2, 2, 2});
q.add(new int[] {2, 4, 2});
q.add(new int[] {3, 3, 2});
q.add(new int[] {3, 1, 2});
q.add(new int[] {2, 7, 1});
q.add(new int[] {4, 7, 1});
我想要获取排序后的队列 Queue<int[]>
数据:
2 7 1
4 7 1
2 2 2
2 4 2
3 1 2
3 3 2
英文:
I am trying to sort with PriorityQueue
and Comparator
, but I don't know how to write method..
If third element is the same, I want to compare it to the first element. If the first element is also the same, i want to compare it to the second element.
I tried to write in compare method :
if(o1[2]<o2[2])
return 1;
else if(o1[2]>o2[2])
return -1;
return 0;
but not working.. plz hele me...
Queue<int[]> q = new PriorityQueue<int[]>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return 0;
}
});
q.add(new int[] {2, 2, 2});
q.add(new int[] {2, 4, 2});
q.add(new int[] {3, 3, 2});
q.add(new int[] {3, 1, 2});
q.add(new int[] {2, 7, 1});
q.add(new int[] {4, 7, 1});
I want to get Queue<int> datas
2 7 1
4 7 1
2 2 2
2 4 2
3 1 2
3 3 2
答案1
得分: 0
使用数组的不同部分进行比较。如果得到差异,返回该差异,以便进行排序。如果没有得到差异,使用另一个数组索引进行另一次比较。因此,在您的情况下,对于third -> first -> second,使用索引2、0,然后1。
public int compare(int[] o1, int[] o2) {
int out = compareUsingIndex(2, o1, o2);
if (out != 0) {
return out;
}
out = compareUsingIndex(0, o1, o2);
if (out != 0) {
return out;
}
return compareUsingIndex(1, o1, o2);
}
private int compareUsingIndex(int index, int[] o1, int[] o2) {
if (o1[index] == o2[index]) {
return 0;
} else if (o1[index] > o2[index]) {
return 1;
}
return -1;
}
英文:
Do your comparison using different parts of the array. If you get a difference, return it, which allows sorting. If you don't get a difference, do another comparison using another array index. So in your case for third -> first -> second, use indexes 2, 0 and then 1.
public int compare(int[] o1, int[] o2) {
int out = compareUsingIndex (2, o1, o2);
if (out !=0){
return out;
}
out = compareUsingIndex (0, o1, o2);
if (out !=0){
return out;
}
return compareUsingIndex (1, o1, o2);
}
private int compareUsingIndex(int index, int[] o1, int[] o2){
if (o1[index]==o2[index]){
return 0;
}
else if (o1[index]>o2[index]){
return 1;
}
return -1;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论