Notice
Recent Posts
Recent Comments
Link
«   2025/12   »
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
Tags more
Archives
Today
Total
관리 메뉴

jeongwon

[백준 JAVA] 4344번 - 평균은 넘겠지 본문

오늘의 문제

[백준 JAVA] 4344번 - 평균은 넘겠지

jeongwon_ 2022. 5. 30. 00:40

나의 답안 : 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main{
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
        
		String[] arr = new String[Integer.parseInt(br.readLine())];		

		for(int i=0; i<arr.length; i++)
			arr[i]=br.readLine();

		double tot, avg, cnt;
		double[] n;

		for(int i=0; i<arr.length; i++) {
			
			tot=0; avg=0; cnt=0;
			
			st=new StringTokenizer(arr[i]," ");
			n=new double[Integer.parseInt(st.nextToken())];	

			for(int j=0; j<n.length; j++) {
				n[j]=Double.parseDouble(st.nextToken());
				tot+=n[j];			
			}
			
			avg=tot/n.length;
			
			for(int k=0; k<n.length; k++)
				if(n[k]>avg) cnt++;
			

			System.out.println(String.format("%.3f", (cnt/n.length)*100.0)+"%");
		}//end of outer for

		br.close();
	}
}

맞았지만 오늘도 어쩐지 구구절절(?)해 보이는 코드.

 

 

개선 답안 : 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main{
	public static void main(String[] args) throws IOException{
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));			
		int casenum = Integer.parseInt(br.readLine());
		StringTokenizer st;
		int[] arr;	
        		
		for(int i=0; i<casenum; i++) {
			double tot, avg, cnt;
			tot=0; avg=0; cnt=0;
            
			st = new StringTokenizer(br.readLine()," ");
			int n = Integer.parseInt(st.nextToken()); //반별 학생수
			arr = new int[n];
						
			for(int j=0; j<n; j++) {	
				arr[j] = Integer.parseInt(st.nextToken());
				tot+=arr[j];			
			}
			
			avg = (tot/n);
			cnt = 0;
			
			for(int k=0; k<n; k++)
				if(arr[k]>avg) cnt++;
			
			System.out.printf("%.3f%%\n",(cnt/n)*100)	;// printf에서 %는 %%
			
		}				
		br.close();
	}
}

String 배열을 없애고 테스트케이스  변수를 추가했다. 속도 개선은 물론, 메모리도 3000KB 가량 줄었다. 

 

'오늘의 문제' 카테고리의 다른 글

[백준 JAVA] 11654번 - 아스키 코드  (0) 2022.06.02
[백준 JAVA] 1065번 - 한수  (0) 2022.06.01
[백준 JAVA] 8958번 - OX 퀴즈  (0) 2022.05.28
[백준 JAVA] 1546번 - 평균  (0) 2022.05.27
[백준 JAVA] 3052번 - 나머지  (0) 2022.05.27