英文:
Custom Comparator is not doing enough Comparison
问题
如果i和j位置的值之和为奇数,则只应交换这些值。输出的字符串应该是按字典顺序最小的。
你可以使用以下代码来实现这个功能:
Collections.sort(list, new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
if ((a + b) % 2 != 0) {
return a - b;
} else {
return a.compareTo(b);
}
}
});
这段代码会根据你描述的条件对列表进行排序,以得到所需的输出。
英文:
I want to sort values based on following criteria:
If sum of values at i & j is odd then only values should be swapped. Output string should be lexicographically smallest possible.
Input: 1 2 5 3 8 10 32 51 5 8<br/>
Output: 1 2 5 3 8 10 32 51 5 8<br/>
Desired Output: 1 2 5 3 5 10 32 8 8 51<br/>
I'm using this piece of code. but it is not giving desired result.
Collections.sort(list, new Comparator<Integer>()
{
public int compare(Integer a, Integer b) {
if ((a + b) % 2 != 0)
return a - b;
else
return 0;
}
});
答案1
得分: 1
你不能这样做。有关 Comparator.compare
的文档指出:
> 最后,实现者必须确保对于所有 z,compare(x, y) == 0 意味着 sgn(compare(x, z)) == sgn(compare(y, z))。
但是你的 Comparator
在 x = 0
,y = 2
,z = 1
时不满足这个条件。
0 == 2
0 < 1
2 > 1
这不是你的实现的问题,而是你尝试做的事情的问题。
英文:
You can't do that. The documentation for Comparator.compare
says
> Finally, the implementor must ensure that compare(x, y) == 0 implies that sgn(compare(x, z)) == sgn(compare(y, z)) for all z.
But your Comparator
does not meet this condition when x = 0
, y = 2
, z = 1
.
0 == 2
0 < 1
2 > 1
This is not a problem of your implementation, but of what you are trying to do.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论