본문 바로가기

컴퓨터/코테

릿코드 876 - Middle of the Linked List

class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        ans = 0
        cur = head
        while cur :
            ans += 1
            cur = cur.next
            
        ans = math.ceil(ans/2) if ans % 2 else ans/2 + 1
        cur = head
        for i in range(int(ans)-1) : 
            cur = cur.next
        return cur

3n/2 번의 연산에 결과를 내는 코드. 

 

class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        ans = 0
        node = []
        cur = head
        while cur :
            node.append(cur)
            ans += 1
            cur = cur.next
            
        idx = math.ceil(ans/2) if ans % 2 else ans/2 + 1
        return node[int(idx)-1]

 

 

 

 

공간 복잡도를 포기하고 n 번만에 결과를 내도록 해봤는데 오히려 이전 코드가 더 빨랐다..

 

'컴퓨터 > 코테' 카테고리의 다른 글