티스토리 뷰
Maximum Twin Sum of a Linked List - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
연결 리스트가 주어졌을때, twin 노드를 더했을때 가장 큰 값을 구하라고 합니다.
간단하게 문제를 해석해보면, 주어진 연결리스트를 list1이라고 두고, list1을 뒤집은 연결 리스트를 list2라고 정의합니다. 이제 리스트를 순환하면서 list1[i] + list2[i] 의 값을 모두 구하고, 이중 최댓값을 구하면 됩니다.
시간복잡도는 배열의 길이가 N일때 O(3N)이 소요되므로 O(N)으로 잡을 수 있습니다.
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
import kotlin.math.max
class Solution {
fun pairSum(head: ListNode?): Int {
var list1 = getList(head)
var current = reverse(head)
var list2 = getList(current)
var answer : Int = 0
for(i in 0..list1.size-1) {
answer = max((getValue(list1, i) + getValue(list2, i)), answer)
}
return answer
}
fun reverse(head : ListNode?) : ListNode? {
var prev : ListNode? = null
var current : ListNode? = head
var next : ListNode? = null
while(isNotNull(current)) {
next = current?.next
current?.next = prev
prev = current
current = next
}
return prev
}
fun isNotNull(node : ListNode?) : Boolean = (node != null)
fun getList(head : ListNode?) : MutableList<Int?> {
var list : MutableList<Int?> = mutableListOf()
var node : ListNode? = head
while(isNotNull(node)) {
list.add(node?.`val`)
node = node?.next
}
return list
}
fun getValue(list : MutableList<Int?>, index : Int) : Int = list[index] ?: 0
}
'PS > LeetCode' 카테고리의 다른 글
[Kotlin] LeetCode 1561 : Maximum Number of Coins You Can Get (0) | 2022.12.04 |
---|---|
[Kotlin] LeetCode 2079 : Watering Plants (0) | 2022.12.03 |
[Kotlin] LeetCode 1302 : Deepest Leaves Sum (0) | 2022.11.28 |
[Kotlin] LeetCode 1588 : Sum of All Odd Length Subarrays (0) | 2022.11.27 |
[Kotlin] LeetCode 1512 : Number of Good Pairs (0) | 2022.11.27 |