Leetcode: Algorithm

发布时间 2023-07-06 02:19:03作者: PEAR2020

1. Boyer-Moore Voting Algorithm

identify the majority element (frequency > n/2)

 

class Solution {
    public int majorityElement(int[] nums) {
        int count = 0;
        Integer candidate = null;

        for (int num : nums) {
            if (count == 0) {
                candidate = num;
            }
            count += (num == candidate) ? 1 : -1;
        }

        return candidate;
    }
}