DEV Community

Debesh P.
Debesh P.

Posted on

169. Majority Element | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/majority-element/


leetcode 169


Solution

we have used Boyer–Moore Voting Algorithm to solve this problem.

class Solution {
    public int majorityElement(int[] nums) {
        int candi = 0;
        int count = 0;

        for(int num : nums) {
            if(count == 0) {
                candi = num;
            }
            if(num == candi) {
                count++;
            }
            else {
                count--;
            }
        }

        return candi;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)