반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 1721 | Swapping Nodes in an Linked List | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/swapping-nodes-in-a-linked-list/
문제
You are given the head of a linked list, and an integer k.
Return the head of the linked list after swapping the values of the $k^{th}$ node from the beginning and the $k^{th}$ node from the end (the list is 1-indexed).
조건
- The number of nodes in the list is n.
- 1 <= k <= n <= $10^5$
- 0 <= Node.val <= 100
내 풀이
리스트의 길이(N)를 잰다.
k번째와 N-k+1번째의 val을 바꾼다.
코드
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
N = 1
count, first, second = head, head, head
while count.next:
count = count.next
N += 1
k1 = min(k, N-k+1)
k2 = N-k1+1
while k2 > 1:
if k1 > 1:
first = first.next
k1 -= 1
second = second.next
k2 -= 1
temp = first.val
first.val = second.val
second.val = temp
return head
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 923 | 3Sum With Multiplicity | Python (0) | 2022.04.06 |
---|---|
[LeetCode] 11 | Container With Most Water | Python (0) | 2022.04.05 |
[LeetCode] 344 | Reverse String | Python (0) | 2022.04.01 |
[LeetCode] 410 | Split Array Largest Sum | Python (0) | 2022.03.31 |
[LeetCode] 74 | Search a 2D Matrix | Python (0) | 2022.03.30 |
Comments