-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindMode3.java
More file actions
44 lines (39 loc) · 1.52 KB
/
Copy pathFindMode3.java
File metadata and controls
44 lines (39 loc) · 1.52 KB
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
package week01.advanced;
import java.util.Scanner;
public class FindMode3 {
public static void main(String[] args) {
System.out.println("<배열에서 최빈값3(가장 자주 나온 수)>");
// 25단계 (심화): 배열에서 최빈값(가장 자주 나온 수) 찾기
// 문제: 정수가 들어있는 배열에서 가장 많이 등장하는 숫자를 찾는 프로그램을 작성하세요.
// 만약 최빈값이 여러 개라면 그중 아무거나 하나만 출력하면 됩니다.
// 핵심 사고: 각 숫자가 몇 번 나왔는지 효율적으로 세는 방법.
// (힌트: 또 다른 배열을 카운팅 용도로 사용)
// 힌트: `배열`, `이중 for문`, `카운팅을 위한 변수 또는 배열`
int maxCnt = 0;
int maxNum = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("숫자를 원하는만큼 입력하세요.>");
System.out.println("(*띄어쓰기로 숫자를 구분하여 주세요.*)");
String inputNum = scanner.nextLine();
String [] str = inputNum.split(" ");
int [] num = new int[str.length];
for(int i=0; i<str.length;i++) {
num[i] = Integer.parseInt(str[i]);
}
// 이중 포문 이용 버전(자리수 상관X)
for(int i=0; i<num.length;i++) {
int cnt = 0;
for(int j=0; j<num.length; j++) {
if(num[i]==num[j]) {
cnt++;
}
}
if(cnt>maxCnt) {
maxCnt=cnt;
maxNum=num[i];
}
}
System.out.println("최빈값 "+maxNum+"은(는) "+maxCnt+"번 나왔습니다.");
scanner.close();
}
}