1204 최빈수 구하기

Sungmin·2023년 11월 1일
0

SWEA 알고리즘

목록 보기
12/26

최빈수 구하기 URL

내 풀이

import java.io.*;
import java.util.*;
 
public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());
 
        for (int t = 1; t <= T; t++) {
            int[] score = new int[101];
            int N = Integer.parseInt(br.readLine());
            StringTokenizer st = new StringTokenizer(br.readLine());
            for (int i = 0; i < 1000; i++) {
                int x = Integer.parseInt(st.nextToken());
                score[x]++;
            }
            int max = Arrays.stream(score).max().getAsInt();
             
            int result = 0;
            for (int i = 0; i < score.length; i++) {
                if (score[i] == max) {
                    result = i;
                }
            }
            System.out.println("#" + t + " " + result);
        }
    }
}

처음에 제출했던 방식인데 다른 사람들보다 메모리 사용량과 실행시간이 비 효율적인것을 보고 어떤 부분에서 비 효율적이었을까 고민해 보았다.

문제는 자주사용하지 않던 stream으로 배열을 정렬하며 max값을 찾는 방식이 가독성적인 측면에선 좋지만 성능적 측면에서는 비교적 덜 효율적인걸 알수 있었다.

Solution

import java.io.*;
import java.util.*;

public class SW1204 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());

        for (int t = 1; t <= T; t++) {
            int[] score = new int[101];
            int N = Integer.parseInt(br.readLine());
            StringTokenizer st = new StringTokenizer(br.readLine());
            for (int i = 0; i < 1000; i++) {
                int x = Integer.parseInt(st.nextToken());
                score[x]++;
            }
            // int max = Arrays.stream(score).max().getAsInt();
            
            int result = 0;
            int max = 0;
            for (int i = 0; i < score.length; i++) {
                if (score[i] >= max) {
                    max = score[i];
                    result = i;
                }
            }
            System.out.println("#" + t + " " + result);
        }
    }
}

Stream 사용한 경우

max변수를 만들어 score.length만큼 반복한 경우

배운점

max변수를 만들어 score.length만큼 반복하는것이 비교적 효율적인걸 알 수 있었다.
생각보다 차이가 많이났다.

profile
Let's Coding

0개의 댓글