알고리즘 풀이/Codility

Codility - Dominator (Leader)

배게 2019. 12. 13. 19:08
728x90
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    public int solution(int[] A) {
        // write your code in Java SE 8
        
        if(A.length==0return -1;
        
        
        HashMap<Integer, Integer> hm = new HashMap<>();
        int max=1;
        for(int a : A){
            if(!hm.containsKey(a)) hm.put(a,1);
            else {
                hm.put(a, hm.get(a)+1);
                if(max<hm.get(a)) max=hm.get(a);
            }
        }
        // System.out.println(max);
        if(max<=A.length/2) {
            // System.out.println("zzz");   
            return -1;
        }
        
        System.out.println(max);
        
        int dominator = 0;
        
        for(int key : hm.keySet()){
            if(max==hm.get(key)){
                dominator = key;
            }
        }
        
        for(int i=0; i<A.length; i++){
            if(A[i]==dominator) return i;
        }
        
        return -1;
    }
cs