본문 바로가기

Backend/Algorithm

6. Math.max , ArrayList - 모의고사

 

 

입출력 예:

answers                                                                            return

[1,2,3,4,5] [1]
[1,3,2,4,2] [1,2,3]

 

 

 

코드:

 

 

import java.util.ArrayList;
public class Solution {
	public int[] solution(int[] answers) {
        int[] answer = {};
        int[] person1 = {1,2,3,4,5};
        int[] person2 = {2,1,2,3,2,4,2,5};
        int[] person3 = {3,3,1,1,2,2,4,4,5,5};
        
        int[] count = new int[3];
        
        for (int i=0; i<answers.length; i++) { 
        	if(answers[i] == person1[i%person1.length]) count[0]++; 
        	if(answers[i] == person2[i%person2.length]) count[1]++;
        	if(answers[i] == person3[i%person3.length]) count[2]++;        	
        }
        
        int max = Math.max(Math.max(count[0], count[1]), count[2]);
        
        ArrayList<Integer> list = new ArrayList<Integer>();
        if (max == count[0]) list.add(1); 
        if (max == count[1]) list.add(2); 
        if (max == count[2]) list.add(3);
        
        answer = new int[list.size()];
        
        for(int i =0; i<answer.length; i++) {
        	answer[i] = list.get(i);
        }
        
        return answer;
    }

}

 

 

 

 

접근방법: