Wednesday, February 18, 2015

Majority Element

Problem:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.


Solution:

class Solution {
public:
    int majorityElement(vector<int> &num) {
        int elem, count = 0;
        int size = num.size();
        if (size == 1)
            return num[0];
        
        for (int i = 0; i < size; i++) {
            if (count == 0) {
                elem = num[i];
                count = 1;
            } else if (elem == num[i]) {
                count++;
            } else {
                count--;
            }
        }
        return elem;
    } 
};

No comments:

Post a Comment