A short Java solution based on voting and foreach


  • -1
    K

    This solution is similar to many others which is based on voting. Using foreach iteration to make it look clear.

    public int majorityElement(int[] num) {
        int major = 0, count = 0;
        for (int e : num) {
            major = (count == 0) ? e : major;
            count += (e == major) ? 1 : -1;
        }
        return major;
    }

  • -2
    G

    if we test the num = {1,2,3,2}, then we got the ans major = 3.

    this program work only when num is sorted.


  • 0
    K

    "The majority element is the element that appears more than ⌊ n/2 ⌋ times". So if you want "2" to be the majority, "2" must appear three or more times in your test case.


  • 0
    G

    sorry, I make a mistake...I thought the majority is equal or more than ⌊ n/2 ⌋.


Log in to reply
 

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