NewGen

알고리즘 연습 iOS / Stack, Queue 본문

IOS

알고리즘 연습 iOS / Stack, Queue

Deep Learning 2021. 1. 9. 17:10

늘 기본이 중요하다고 생각함.

늘 기초를 연습해두어야 함.

 

 

 

대략 저렇게...

문제가 주어지고..

처음에는 다리길이만큼 Queue Array로 잡고 무게값 총합을 계속 계산하면서 돌았더님나..시간초과가 계속 걸려서..

그냥 총량을 더하고 뺄때마다 변수하나에 저장하여 돌리니 시간초과가 안걸렸슴

 

코드

func solution(_ bridge_length:Int, _ weight:Int, _ truck_weights:[Int]) -> Int {

        var test : [Int] = truck_weights

            var t : Int = 0;

            

            if(test.count == 1) {

                return bridge_length+1

            }

            

            

            var time_arr : [Int] = [Int](repeating: 0, count: bridge_length)

            

            var tot : Int = 0

            

            while(true) {

                if(test.count > 0) {

                    if(tot+test[0]) <= weight {

                        if(time_arr[0] > 0) {

                            tot -= time_arr[0]

                        }

                        time_arr.remove(at: 0)

                        time_arr.append(test[0])

                        tot += test[0]

                        test.remove(at: 0)

                    }else{

                        if(time_arr[0] > 0) {

                            tot -= time_arr[0]

                        }

                        time_arr.remove(at: 0)

                        

                        if(tot+test[0]) <= weight {

                            time_arr.append(test[0])

                            tot += test[0]

                            test.remove(at: 0)

                        }else{

                            time_arr.append(0)

                        }

                    }

                    t += 1

                }else{

                    for x in 0..<time_arr.count {

                        tot -= time_arr[x]

                        t += 1

                        if(tot <= 0)

                        {

                            break;

                        }

                    }

                }

                

                print("tot=\(tot), t=\(t), time_arr=\(time_arr), test=\(test)")

                if(tot <= 0)

                {

                    break;

                }

                

            }

            

          

            return t

    }

 

다리를지나는트럭.txt
0.00MB

 

Comments