如何在Python中定义排序绑定规则?

时间:2017-10-31 04:37:32

标签: python algorithm sorting

我尝试使用max heap实现算法来解决天际线问题。我试图实现的算法的一部分是以特定方式解决关系。该解决方案的作者使用Java中的以下代码覆盖compareTo方法(完整代码可在此处找到https://github.com/mission-peace/interview/blob/master/src/com/interview/geometry/SkylineDrawing.java

    @Override
    public int compareTo(BuildingPoint o) {
        //first compare by x.
        //If they are same then use this logic
        //if two starts are compared then higher height building should be picked first
        //if two ends are compared then lower height building should be picked first
        //if one start and end is compared then start should appear before end
        if (this.x != o.x) {
            return this.x - o.x;
        } else {
            return (this.isStart ? -this.height : this.height) - (o.isStart ? -o.height : o.height);
        }
    }

我如何在Python中实现它?我知道我可以在sorted()函数中指定关键参数,但我不确定如何进行此示例。谢谢!

编辑1:

示例(s = start,e = end):

Input = [[0,2,'s'], [0,3,'s'], [1,2,'e'], [1,3,'e']]

output = [[0,3,'s'], [0,2,'s'], [1,2,'e'], [1,3,'e']]

Input = [[4,2,'s'], [3,3,'s'], [5,3,'e'], [5,2,'e']]

output = [[3,3,'s'], [4,2,'s'], [5,2,'e'], [5,3,'e']]

Input = [[7,3,'s'], [8,3,'e']], [6,2,'s'], [7,2,'e']

output = [[6,2,'s'], [7,3,'s'], [7,2,'e'], [8,3,'e']]

0 个答案:

没有答案