알고리즘/프로그래머스 Level2

[프로그래머스,Java] Level2: 혼자 놀기의 달인

류창 2022. 11. 12. 22:55

 

문제 분석:

 

해당 문제를  요약하자면,

 

1. 무작위로 나열된 카드가 존재함.

2. idx 0번부터 탐색 

3. idx 0번의 카드를 꺼내, 그 카드의 숫자에 적힌 idx 상자를 뽑는다.

4. 3번의 행동을 반복하여  하나의 싸이클(순환)이 될때까지 수행한다. 우린 이걸 하나의 그룹으로 명한다.

5. 그렇게 만들어진 그룹중에서 제일 사이즈가큰 2개의 곱을 반환

 

 

문제를 제대로 이해가 완료했다면,  이제 푸는방법은 꽤나 간단하다.

 

이 로직을 구현하기위해선 3가지 

 

1. 방문을 체크할 boolean[] 

2. 모든 상자를 탐색할 for문

3. 싸이클(순환) 을 탐색할 while문을 준비한다.

 

싸이클 순환동안 매번  카드의 값이 바뀌기때문에 체크를해줄

current를 하나 생성해서 판별한다.

문제 풀이:

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
import java.util.*;
class Solution {
    public int solution(int[] cards) {
        int answer = 0;
          
        boolean[] visit = new boolean[cards.length+1];
        
        List<Integer> list = new ArrayList<>();
        
        for(int i=0;i<cards.length;i++){
            
            if(visit[cards[i]]){
               continue
            }
            
            int current=cards[i];
            int count =0;
            
            while(true){
                             
                if(visit[current]){
                    break;
                }
                count++;
                
                visit[current]=true;
                
                current=cards[current-1];
            }
            
            list.add(count);          
        }
        
        if(list.size()<2){
            return 0;
        }
        
        Collections.sort(list,Collections.reverseOrder());
        
        answer=list.get(0)*list.get(1);
        
        return answer;
    }
}
cs