코딩테스트

[프로그래머스/Java] 모의고사 (ArrayList 개념)

데메즈 2026. 7. 8. 07:58
반응형

https://school.programmers.co.kr/learn/courses/30/lessons/42840

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

int[] 는 처음에 정한 크기를 바꿀 수 없기 때문에 데이터가 몇 개 들어올지 모르는 대부분의 코테 문제에서는

무조건 ArrayLists를 먼저 쓰고 시작한다.

 

// 선언
ArrayList<Integer> list = new ArrayList<>();

 

1. 데이터 추가 : add(값)

리스트의 맨 뒤에 데이터를 추가한다

list.add(10);
list.add(20); // [10, 20]

 

2. 데이터 가져오기 : get(인덱스)

int val = list.get(0); // 0번째 값인 10을 가져옴

 

3. 데이터 개수 확인 : size()

int count = list.size(); // 결과 : 2

 

4. 데이터 포함 여부 : contains(값)

리스트 안에 특정 값이 존재하는지 true / false 로 알려준다

if(list.contains(20)){ // true

	...
}

 

5. 데이터 정렬 : Collections.sort(list)

import java.util.Collections;

Collections.sort(list); // 오름차순 정렬
Collections.sort(list, Collections.reverseOrder()); // 내림차순 정렬

 

6. 리스트 비우기 : clear()

리스트 안의 모든 데이터를 한번에 삭제. 그래프 탐색이나 탐색 조건을 초기화할 때 간혹 쓰인다

list.clear(); // [] 빈 상태가 됨

 

7. ArrayList를 int[]로 바꾸기

int[] answer = new int[list.size()];
for(int i=0; i<list.size(); i++){
	answer[i] = list.get(i);
}
return answer;

 

 

import java.util.ArrayList;

class Solution {
    public int[] solution(int[] answers) {
        
        int[] first = {1,2,3,4,5};
        int[] second = {2,1,2,3,2,4,2,5};
        int[] third = {3,3,1,1,2,2,4,4,5,5};
        int cnt1 = 0, cnt2 = 0, cnt3 = 0;
        
        for(int i=0; i<answers.length; i++){
            if(first[i%5] == answers[i]) cnt1++;
            if(second[i%8] == answers[i]) cnt2++;
            if(third[i%10] == answers[i]) cnt3++;
        }
        
        int max = Math.max(cnt1, Math.max(cnt2, cnt3));
        
        ArrayList<Integer> list = new ArrayList<>();
        if(cnt1 == max) list.add(1);
        if(cnt2 == max) list.add(2);
        if(cnt3 == max) list.add(3);
        
        int[] answer = new int[list.size()];
        for(int i=0; i<list.size(); i++){
            answer[i] = list.get(i);
        }
        return answer;
        
    }
}
반응형