I have a question for this naive O(n*n) approach

  • 0

    I solved this one with a naive approach, this is accepted by the OJ, which I think the test case of the OJ didn't check for the time complexity at all... During my debugging time, I found an error that I could not understand, you can check it in the command of the code. If I set the index = i at if (t==1) statement and return A[index] instead of returning the -1, to get the correct answer. Any one could help me explain about that unreachable statement? Thanks in advance.

    public int singleNumber(int[] A) {
        int index = 0;
        for (int i = 0; i< A.length; i++){
            int t = 0;
            for (int j = 0; j < A.length; j++){
                if (A[i] == A[j]) {t++;}
                //if (t > 1) break;
            if (t == 1) {return A[i]; break;} //could not return A[i], this makes the statement unreachable, I don't understand this
        return -1;

  • 1

    The question is every element appears 3 times except for one. It doesn't mean that single one appears only 1 time.

Log in to reply

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