Qsort() not allowed?


  • 1
    K

    Hello. Just to clarify, I have my code as follows. It runs on my machine but I get Runtime Error when submitting. When I change qsort() to an bubble sort, no more Runtime Error but I get TLE. So I guess qsort() is not allowed?

    #include <stdlib.h>
    #include <iostream>
    using namespace std;
    class Solution {
    public:
    
        static int cmp(const void *a, const void *b) {
            return (*(int*)a - *(int*)b);
        }
        int singleNumber(int a[], int n) {
            int i =0 ;
            qsort(a, n, sizeof(int), cmp);
            for (i=0;i<n;i++) cout << a[i] << " ";
            if (n>=1 && a[0]!= a[1]) return a[0];
            if (n >=2 && a[n-2] != a[n-1]) return a[n-1];
            for (i=0; i<n-2; i++) 
                if (a[i]!=a[i+1] && a[i+1]!=a[i+2]) return a[i+1];
        }
    };

  • 1
    S

    Do not cout when you submit to judge. It may lead to unexpected error.

    if (n>=1 && a[0]!= a[1]) return a[0]; In this, you do not handle it when n == 1, there is no a[1].


  • 0
    K

    Thank you. That helps.

    Cheers,


  • 0
    D

    Even you fix the problem of "n==1",you still get run time Error,alright?
    I think we cannot get Accepted if using qsort();


  • 0
    M

    Hi Bro, I got the same problem with you. I use qsort in my code and it returns a compile error.

    So just wanna know whether you figure out why qsort fails.


  • 0
    C

    qsort() is nlogn, not n, so not linear time.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.