LinkedNestBlog

Majority Algorithm

by 이진원Dev
Majority Algorithm

ref. : https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm

code :
    // 주어진 배열에서 가장 많이 존재하는 숫자를 출력
    public static int majority(int[] arr){

        int candidate = arr[0];
        int cnt       = 0;
        int size      = arr.length;
        // arr 배열에 가장 많이 존재하는 숫자의 갯수를 counting.
        for(int attr : arr){
            if(cnt == 0){
                candidate = attr;
                cnt = 1;
            } else if(candidate == attr){
                cnt++;    
            } else {
                cnt--;
            }
        }

        cnt = 0;
        for(int attr : arr){
            if(attr == candidate){
                cnt++;
            }
        }

        if(cnt < (size + 1) / 2) return -1;

        return candidate;
    }
Majority Algorithm · LinkedNest Blog