2807. Insert Greatest Common Divisors in Linked List
문제 설명
- 링크드 리스트가 주어진다.
- 각 노드들 사이에 이제 최대공약수 노드를 끼워넣어라 !
문제 풀이
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
}
}
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
을 사용하는 것 정도의 차이가 있을뿐 코드 전체적인 로직은 도일한 것으로 보인다.