소스 보러가기
문제 보러가기


사용한 알고리즘 및 자료구조
Sol 1 : ArrayList, Sol 2 : Stack

풀이
따로 알고리즘 구현이 필요 없는 문제이다. ArrayList, List, Stack 과 같은 자료구조 개념을 알고 있다면 쉽게 풀 수 있는 문제이다.

  1. 열 순서대로 인형 탐색

  2. 인형 있으면 -> 해당 칸 빈칸으로

  3. Stack or List 마지막 칸과 비교 같으면 삭제 후 정답 카운트 증가
    다르면 맨 뒤에 추가

  4. moves배열의 길이만큼 수행했다면 정답 카운트 출력

상당히 간단하다. Stack, List 둘다 가능할 것이라 생각하여 solution을 2개 만들었다.

로직은 같고 차이점은 Stack은 뽑는 행위가 디폴트 값으로 마지막 위치에 인형을 뽑는다. 그리고List는 (인덱스 값-1)을 매개변수로 get()을 이용하여 바구니 마지막 위치에 있는 인형을 출력한다.

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// before test, have to delete 'static' keywords
    public static int solution(int[][] board, int[] moves) {
        int answer = 0;
 
        ArrayList<Integer> box = new ArrayList<Integer>();
 
        for (int idx = 0; idx < moves.length; idx++) {
 
            int row = moves[idx] - 1;
 
            for (int col = 0; col < board.length; col++) {
 
                int boxLastIdx = box.size() - 1;
 
                if (board[col][row] != 0) {
 
                    if (box.isEmpty()) {
                        box.add(board[col][row]);
                    } else {
 
                        if (box.get(boxLastIdx) == board[col][row]) {
 
                            box.remove(boxLastIdx);
                            answer += 2;
                        } else {
                            box.add(board[col][row]);
                        }
 
                    }
                    board[col][row] = 0;
 
                    break;
 
                }
 
            }
 
        }
 
        return answer;
    }
    
 
    public int solution2(int[][] board, int[] moves) {
        Stack<Integer> box = new Stack<Integer>();
 
        int answer = 0;
        for (int i = 0; i < moves.length; i++) {
            int row = moves[i];
            for (int col = 0; col < board.length; col++) {
                if (board[col][row - 1!= 0) {
 
                    if (box.empty()) {
                        box.push(board[col][row-1]);
                    } else {
 
                        if (box.peek() == board[col][row-1]) {
                            box.pop();
                            answer += 2;
                        } else {
 
                            box.push(board[col][row-1]);
                        }
 
                    }
                    board[col][row-1= 0;
 
                    break;
                }
 
            }
 
        }
 
        return answer;
    }
cs

'알고리즘(추가예정) > 기타' 카테고리의 다른 글

[프로그래머스] 베스트앨범  (0) 2020.08.30

소스 보러가기
문제 보러가기


사용한 알고리즘 및 자료구조

HashMap,ArrayList

풀이
문제를 보고 HashMap 사용을 떠올랐다. 가장 먼저 생각한 것은 자바의 콜렉션을 최소화 하여 문제를 풀어내는 것 이었다. 그리고 총 4개의 콜렉션을 사용하여 문제를 풀었다.

먼저 파악해야 될 것은 정렬의 우선순위 요소 파악이다.

“장르 우선순위 , 노래 재생 횟수, 고유번호가 낮은 순서” 이렇게 우선순위가 선정되어 정렬이 된다. 파악한 우선순위로 차례차례 문제를 풀면 간단히 해결이 된다.

  1. 각 장르별로 재생된 횟수 구하여 HashMap에 담기

  2. 노래에 대한 구조체를 만들어 ArrayList에 담기

  3. 정렬하기 : Collections.sort() 함수 이용

  4. 정렬된 ArrayList에서 장르별 순서대로 2개씩 노래 새로운 ArrayList에 담기

간단하게 표현하면 이렇게 4단계로 문제가 풀린다. 자세한건 코드를 보면서 파악하기 바란다.

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
    // before test, have to delete 'static' keywords
    public static int[] solution(String[] genres, int[] plays) {
        HashMap<String, Integer> genresCheck = new HashMap<String, Integer>();
        HashMap<String, Integer> inputCheck = new HashMap<String, Integer>();
        ArrayList<Song> songList = new ArrayList<Song>();
        ArrayList<Integer> outputList = new ArrayList<Integer>();
        //1. genres count
        
        
        
        for(int g_idx = 0; g_idx < genres.length; g_idx++) {
 
            String g_str = genres[g_idx];
            songList.add(new Song(g_str,plays[g_idx],g_idx));
            
            if(genresCheck.containsKey(g_str)) {
                genresCheck.put(g_str, genresCheck.get(g_str)+plays[g_idx]);
            } else {
                
                genresCheck.put(g_str, plays[g_idx]);
            }
            
        }
        //2. sort
        
        Collections.sort(songList, new Comparator<Song>() {
            
            //s1 new
            @Override
            public int compare(Song s1, Song s2) {
                
                if(s1.genresName.equals(s2.genresName)) {
                    
                    if(s1.playCount != s2.playCount) {
                        return - (s1.playCount - s2.playCount);
                    } else {
                        
                        return (s1.songNum - s2.songNum);
                    }
                    
                } else {
                    
                    return -(genresCheck.get(s1.genresName) - genresCheck.get(s2.genresName));
                    
                }
                
            }
            
            
        }); 
        //3.checking
        for(int idx = 0; idx < songList.size(); idx++) {
            
            Song song = songList.get(idx);
            
            if(!inputCheck.containsKey(song.genresName)) {
                inputCheck.put(song.genresName, 1);
                outputList.add(song.songNum);
            } else {
                
                int cnt = inputCheck.get(song.genresName);
                
                if(cnt > 1) {
                    continue;
                } else {
                    inputCheck.put(song.genresName, cnt+1);
                    outputList.add(song.songNum);
 
                }
                
            }
            
        }
        
        int[] answer = new int[outputList.size()];
        
        for(int s_idx = 0; s_idx < answer.length; s_idx++) {
            answer[s_idx] = outputList.get(s_idx);
        }
 
 
        return answer;
    }
 
    static class Song {
        
        String genresName;
        int playCount;
        int songNum;
 
        public Song(String genresName, int playCount, int songNum) {
            
            this.genresName = genresName;
            this.playCount = playCount;
            this.songNum = songNum;
 
        }
 
    }
 
cs

'알고리즘(추가예정) > 기타' 카테고리의 다른 글

[프로그래머스] 인형뽑기  (0) 2020.08.30

+ Recent posts