自定义比较器未进行足够的比较。

huangapple go评论63阅读模式
英文:

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&lt;Integer&gt;()
        {
            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))。

但是你的 Comparatorx = 0y = 2z = 1 时不满足这个条件。

0 == 2
0 &lt; 1
2 &gt; 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 &lt; 1
2 &gt; 1

This is not a problem of your implementation, but of what you are trying to do.

huangapple
  • 本文由 发表于 2020年9月28日 04:10:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64092870.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定