| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- jwt
- 클론코딩
- 0.75px border
- 으
- 0.5px border
- 1px border
- entity
- 문서번호
- 0.25px border
- &연산
- Websocket
- 서버리스 #
- 당근마켓
- ZOOM
- es6
- angular
- ES5
- TS
- literal
- font-size
- 전역변수
- Props
- github
- 10px
- Strict
- 데이터베이스 #try #이중
- 컴포넌튼
- TypeScript
- npm
- 타입스크립트
Archives
- Today
- Total
복잡한뇌구조마냥
[코딩테스트 + Java] 최빈값구하기 - 프로그래머스 Lv.0 본문
문제

for 문을 이용한 풀이
import java.util.Arrays;
class Solution {
public int solution(int[] array) {
// 배열 정렬
Arrays.sort(array);
// 첫번째 요소 기준으로 값 초기화
int answer = array[0];
int prevNum=array[0];
int maxCount=1;
int count=1;
for (int i = 1; i<array.length; i++){
int currNum = array[i];
// 값이 변경되면 1, 동일하면 count + 1;
count = prevNum != currNum ? 1 : count+1;
if (maxCount < count){
// 최대 카운트가 변경되면 최빈값 변경
maxCount = count;
answer = prevNum;
} else if (maxCount == count){
// 최빈값이 동일하면 -1 반환
answer = -1;
}
prevNum = currNum;
}
return answer;
}
}
HashMap을 이용한 풀이

import java.util.Map;
import java.util.HashMap;
class Solution {
public int solution(int[] array) {
int answer = -1;
Map<Integer, Integer> map = new HashMap<>();
// Key : Value 형식으로 삽입
for(int num : array){
if (map.containsKey(num)) map.put(num, map.get(num)+1);
else map.put(num,1);
}
int max= -1;
// 최대 값 계산 및 최빈값 중복 확인
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int count = entry.getValue();
if(count > max){
answer = entry.getKey();
max = count;
} else if (count == max){
answer = -1;
}
}
return answer;
}
}
참고자료:
https://school.programmers.co.kr/learn/courses/30/lessons/120812
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
구글 검색
https://www.google.com/search?q=%EC%9E%90%EB%B0%94+java.util.hashmap
🔎 자바 java.util.hashmap: Google 검색
www.google.com
LIST
'공통 > 알고리즘 및 코테' 카테고리의 다른 글
| [코딩테스트 + Java] 문자 반복 출력하기 - 프로그래머스 Lv.0 (0) | 2025.07.07 |
|---|---|
| [코딩테스트 + JAVA] 기능개발 - 프로그래머스 Lv.2 (0) | 2025.07.02 |
| [알고리즘] 완전 탐색 - 부분집합 (0) | 2025.05.18 |
| [자료구조] 개념 정리 (7) | 2025.05.18 |
| [알고리즘] 다익스트라 (Dijkstra`s Algorithm) (0) | 2025.05.17 |