/* 최빈값 구하기
* 최빈값은 주어진 값 중에서 가장 자주 나오는 값을 의미합니다.
* 정수 배열 array가 매개변수로 주어질 때, 최빈값을 return
* 최빈값이 여러 개면 -1을 return 합니다.
*
* array result
* [1, 2, 3, 3, 3, 4] 3
* [1, 1, 2, 2] -1
* [1] 1
*/
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | import java.util.*; public class Programmer_0_33 { static int[] a1 = {1, 2, 3, 3, 3, 4}; static int[] a2 = {1, 1, 2, 2}; static int[] a3 = {1}; public int getChk(List<Map<String,Object>> listAr, int val){ int chk = 0; for(Map<String,Object> mp : listAr){ if(mp.get("val").equals(val)) chk++; } return chk; } public int solution(int[] array) { int answer = 0; /* 다른사람 풀이 int maxCount = 0; int answer = 0; Map<Integer, Integer> map = new HashMap<>(); for(int number : array){ int count = map.getOrDefault(number, 0) + 1; if(count > maxCount){ maxCount = count; answer = number; } else if(count == maxCount){ answer = -1; } map.put(number, count); } */ Arrays.sort(array); List<Map<String, Object>> rstAr = new ArrayList<Map<String, Object>>(); int max = 0; for(int i = 0; i < array.length; i++){ Map<String, Object> rstMp = new HashMap<String, Object>(); int cnt = 0; for(int k = 0; k < array.length; k++){ if(array[i] == array[k]) cnt++; } if(getChk(rstAr, array[i]) == 0){ rstMp.put("val", array[i]); rstMp.put("cnt", cnt); rstAr.add(rstMp); } } for(int i = 0; i < rstAr.size(); i++){ System.out.println(rstAr.get(i)); } for(int i = 0; i < rstAr.size(); i++){ Map<String, Object> mp = rstAr.get(i); if((int)mp.get("cnt") > max){ max = (int) mp.get("cnt"); answer = (int)mp.get("val"); } } int chk = 0; for(Map<String,Object> tst : rstAr){ if(max == (int) tst.get("cnt")) chk++; } if(chk > 1) answer = -1; return answer; } public static void main(String args[]){ Programmer_0_33 t = new Programmer_0_33(); System.out.println("---------------------------------------"); System.out.println("result = " + t.solution(a1)); System.out.println("---------------------------------------"); System.out.println("result2 = " + t.solution(a2)); System.out.println("---------------------------------------"); // System.out.println("result3 = " + t.solution(a3)); // System.out.println("---------------------------------------"); } } | cs |