75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

169. Majority Element (Easy)

O(N^2) Brute force

O(N)Time with extra space

Moore’s Voting Algorithm

class Solution {
public:
    // moore's voting algorithm
    int majorityElement(vector<int>& nums)
    {
        int count = 0;
        int candidate = 0;
        for (int x : nums) {
            if (count == 0) {
                candidate = x;
            }
            // count += (x == candidate) ? 1 : -1;
            if (x == candidate) count++;
            else count--;
        }
        return candidate;
    }
};