[Swift] [71일차] 2807_LEET

·2025년 2월 16일
0

SwiftAlgorithm

목록 보기
74/105

2807. Insert Greatest Common Divisors in Linked List


문제 설명

  1. 링크드 리스트가 주어진다.
  2. 각 노드들 사이에 이제 최대공약수 노드를 끼워넣어라 !

문제 풀이

class Solution {
    func GCD(_ a : Int , _ b : Int) -> Int {
        if b == 0 {
            return a
        }
        return GCD(b, a % b)
    }
    func insertGreatestCommonDivisors(_ head: ListNode?) -> ListNode? {
        // 끝까지 도는 방법
        var answer = head
        var current = head
        
        while(current?.next != nil){
            print(GCD(current?.val!,current?.next?.val!))
            
            current = current?.next
        }
        return head
    }
}

이런식으로 해주다가, 이게 결국에는 두개를 봐야하는데, 변수를 두개만들어서 하자니 좀 어긋나는거 같고해서, 이전에 사용하고자했던 while let을 사용해서 풀이를 진행했다.


class Solution {
    //GCD 코드 생략 ,, 위와 동일
    
    func insertGreatestCommonDivisors(_ head: ListNode?) -> ListNode? {
        // 끝까지 도는 방법
        var answer = head
        var current = head
        
        while let node = current, let nextNode = node.next{
            let gcdTmp = GCD(node.val, nextNode.val)
            let gcdNode = ListNode(gcdTmp,nextNode) //중간이니까 두번째랑 연결
            
            node.next = gcdNode // 첫번째친구랑 연결 
            current = nextNode  // 이제 중간꺼 넘겨서 이제 두번째꺼가 첫번째로 
            
        }
        return answer
    }
}

준수한 것 같은데 왜 느리지? 싶어서 좀 보다가.. 이거 return answer 대신에 그냥 주어진 head를 바로 return해주게 수정을 진행했더니

func insertGreatestCommonDivisors(_ head: ListNode?) -> ListNode? {
        // 끝까지 도는 방법
        var current = head
        
        while let node = current, let nextNode = node.next{
            let gcdTmp = GCD(node.val, nextNode.val)
            let gcdNode = ListNode(gcdTmp,nextNode) //중간이니까 두번째랑 연결
            
            node.next = gcdNode // 첫번째친구랑 연결 
            current = nextNode  // 이제 중간꺼 넘겨서 이제 두번째꺼가 첫번째로 
            
        }
        return head
    }


살짝 개선된 것을 확인할 수 있었다.


최종 제출 코드

class Solution {
    func GCD(_ a : Int , _ b : Int) -> Int {
        if b == 0 {
            return a
        }
        return GCD(b, a % b)
    }
    func insertGreatestCommonDivisors(_ head: ListNode?) -> ListNode? {
        // 끝까지 도는 방법
        var current = head
        
        while let node = current, let nextNode = node.next{
            let gcdTmp = GCD(node.val, nextNode.val)
            let gcdNode = ListNode(gcdTmp,nextNode) //중간이니까 두번째랑 연결
            
            node.next = gcdNode // 첫번째친구랑 연결 
            current = nextNode  // 이제 중간꺼 넘겨서 이제 두번째꺼가 첫번째로 
            
        }
        return head
    }
}

타인의 코드

class Solution {
    func insertGreatestCommonDivisors(_ head: ListNode?) -> ListNode? {
        var current = head
        while let node = current {
            let nextNode = node.next

            if let nextValue = current?.next?.val {
                current?.next = .init(gcd(node.val, nextValue), nextNode)
            }

            current = nextNode
        }

        return head
    }

    func gcd(_ a: Int, _ b: Int) -> Int {
        return b == 0 ? a : gcd(b, a % b)
    }
}

위의 내가 제출한 코드처럼 while let에 두가지 (현재, 다음노드)를 선언해주는 경우도 있지만, 이 분처럼 하나만 선언해주고, 내부에서 if let을 사용하는 것 정도의 차이가 있을뿐 코드 전체적인 로직은 도일한 것으로 보인다.

profile
기억보단 기록을

0개의 댓글