Smallest C Solution in O(N) Time Complexity and O(1) Space Complexity


  • 0
    G
    int count = 0;
    int majority;
    
    for(int i = 0; i < numsSize; i++)
        count == 0 ? ((majority = nums[i]) | (count++)) : majority == nums[i] ? count++ : count--;
    
    return majority;

  • 0

    That gets compile error Line 7: error: not a statement (Line 7 is that ugly long line). And after fixing that, it would get compile error Line 6: error: cannot find symbol: variable numsSize.

    (Edit: Originally the title said it's a Java solution, that's fixed now.)


  • 0
    G
    This post is deleted!

  • 0
    G

    @ManuelP Hey, I'm Sorry it is a C solution. I accidentally wrote Java. You can try again. Thanks.


  • 0

    Ok as C it compiles. But it's wrong. It fails for example for input [0,0,1], incorrectly returning 1 instead of 0. I guess that's what you get for abusing things instead of writing "normal" code :-P

    (Edit: Fixed now. The | was a && before.)


  • 0
    G

    @ManuelP Oh. I thought Leetcode inbuilt test cases will cover that and the solution is foolproof. Thanks for pointing that out.


  • 0
    G

    @ManuelP Hey the solution works now for [0 0 1].


Log in to reply
 

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