codewars054: Who won the election?

Instructions:

Who won the election?java

Solution:

//https://www.codewars.com/kata/554910d77a3582bbe300009c/train/java
import java.util.*;
public class BallotsCounter{
    public static String getWinner(final List<String> listOfBallots){
        if(listOfBallots == null || listOfBallots.isEmpty() || listOfBallots.size() == 2){
            return null;
        }            
        if(listOfBallots.size() == 1){
            return listOfBallots.get(0);
        }    
        Map<String,Integer> map = new HashMap<String,Integer>();
        final int threshold = listOfBallots.size() / 2 + 1;
        for(String x : listOfBallots){
            if(!map.containsKey(x)){
                map.put(x,1);
            }else{
                int value = map.get(x);
                value++;
                if(value >= threshold){
                    return x;
                }else{
                    map.put(x,value);
                }                        
            }                    
        }    
        return null;
    }    
}

Example Tests:

TBD
https://www.codewars.com/kata/554910d77a3582bbe300009c/train/java
相關文章
相關標籤/搜索