반응형

주어진배열에서 제일 많이 나온 값을 도출

array = {1,3,3,4,4,4,4,5}

 

= 4

 

int[] array = {1};

        int answer = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
		
        if (array.length == 1) return array[0];
        
        int[] list = array;
        int t = 1;
        for (int i = 0 ; i<array.length ; i++) {
            for(int j = 1 ; j < list.length-1 ; j ++) {
                if (list[j] == array[i]) {
                    t++;
                    map.put(list[j],t);
                }
            }
            t = 0;
        }

        int test = 0;
        for(int key : map.keySet()) {
            if (map.get(key) > test) {
                test = map.get(key);
                answer = key;
            } else if (map.get(key) == test) {
                answer = -1;
            }
        }
        return answer;

이렇게 했는데 한 케이스만 안됐다.

 

맵으로 어케안되나? 생각하던 중 아래 케이스를 발견했다.

 

성공적인 케이스

import java.util.*;
class Solution {
    public int solution(int[] array) {
        int maxCount = 0;
        int answer = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for(int number : array){
        
           // count = 맵에 저장된 number의 카운트+1 혹은 0 +1
            int count = map.getOrDefault(number, 0) + 1;
            
            //최초 & 기존에 저장된 number를 다시만났을때 오는 곳
            if(count > maxCount){
                maxCount = count;
                answer = number;
            }
            else  if(count == maxCount){
            //count = 1 즉 해당글자가 첫번째 글자일때 들어오는 공간
                answer = -1;
            }
            map.put(number, count);
        }
        return answer;
    }
}

728x90

+ Recent posts