简体   繁体   English

自定义比较器以分离偶数和奇数给定 TLE

[英]Custom comparator to segregate even and odd giving TLE

I am trying to implement the solution for this leetcode problem: https://leetcode.com/problems/sort-array-by-parity/ .我正在尝试实现这个 leetcode 问题的解决方案: https://leetcode.com/problems/sort-array-by-parity/ (ie segregate even and odd elements in an array) (即分离数组中的偶数和奇数元素)

I wrote the below solution using custom comparator in C++:我在 C++ 中使用自定义比较器编写了以下解决方案:

bool custom_cmp(int &l, int &r){
    return l%2 == 0;
}

class Solution {
public:
    vector<int> sortArrayByParity(vector<int>& nums) {
        sort(nums.begin(), nums.end(), custom_cmp);
        return nums;
    }
};

However, the above solution gives me TLE and is apparently taking more than O(n*logn) time.但是,上述解决方案给了我 TLE 并且显然花费了超过 O(n*logn) 时间。

Next, I changed the custom comparator in the above code as follows:接下来,我将上述代码中的自定义比较器更改如下:

bool custom_cmp(int &l, int &r){
    return (l%2 < r%2);
}

The above solution works perfectly fine and is not giving me TLE.上面的解决方案工作得很好,并没有给我 TLE。 Both of the solutions seem to use the same sorting algorithm and the results of the two comparator class also seem the same.两种解决方案似乎都使用相同的排序算法,两个比较器 class 的结果似乎也相同。

Can you help me explain what is the difference between the above two implementations and why the second one works while the first one fails?你能帮我解释一下上述两种实现之间有什么区别,为什么第二个有效而第一个失败?

Your first comparator does not meet the requirements defined by Compare since it doesn't take r 's value into account (ie it does not properly establish a "strict weak ordering").您的第一个比较器不符合Compare定义的要求,因为它没有考虑r的值(即它没有正确建立“严格的弱排序”)。

For example, one requirement that the first comparator violates is:例如,第一个比较器违反的一个要求是:

For all a , comp(a,a)==false对于所有acomp(a,a)==false

Which we can easily break with custom_cmp(0, 0) .我们可以很容易地用custom_cmp(0, 0)打破它。

As an experiment I tried using the same comparator in Compiler Explorer , and interestingly it actually ends up invoking Undefined Behavior because of the unsatisfied contract.作为一个实验,我尝试在Compiler Explorer中使用相同的比较器,有趣的是,由于合同不满意,它实际上最终调用了 Undefined Behavior。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM