관리 메뉴

🌲자라나는청년

[프로그래머스] 다리 건너기(링크드리스트, java) 본문

카테고리 없음

[프로그래머스] 다리 건너기(링크드리스트, java)

JihyunLee 2019. 10. 3. 01:16
반응형

다리건너기( 링크드리스트 )

프로그래머스의 다리 건너기 문제를 링크드리스트를 이용해 풀어 보았다.

 

 

링크드 리스트로 다리를 구현했다. 그래서 문제를 풀기에는 쉬웠는데, 메모리 사용이 많았다.

 

 

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
import java.util.*;
 
class Solution {
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        int answer = 0;
        //bridge를 likedlist로 구현
        //ㅁ-ㅁ-ㅁ-ㅁ-ㅁ-ㅁ
        LinkedList<Integer> bridge = new LinkedList<Integer>();
        
        for(int i=0;i<bridge_length; i++){
            bridge.add(0);
        }
        
        int bridge_current = 0;//current weight of bridge
        int t_idx =0;//truck index;
        int truckNum = truck_weights.length;
        
        while(true){// procedure
            bridge_current -= bridge.pollLast();//out
            
            if(t_idx<truckNum && 
               bridge_current + truck_weights[t_idx]<=weight){//new truck comes
                bridge.addFirst(truck_weights[t_idx]);
                bridge_current += truck_weights[t_idx];
                t_idx ++;
            }
            else{
                bridge.addFirst(0);
            }
            answer ++;
            //System.out.println(bridge_current);
            if( bridge_current ==0){
                break;
            }
        }
        
        return answer;
    }
}
cs

 

맨 마지막 노드를 삭제하는건 .poll명령어 인데 처음에 .get을 썼다가 값이 안나와서 시간이 조금 오래 걸렸다.

반응형