看到以后想到的就是俩俩交换,给一个prev一个cur,然后我居然写出来了!还是挺绕的,但是理清楚以后就还好
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0)
dummy.next = head
prev = dummy
cur = head
while prev and cur and cur.next:
nxt = cur.next.next
prev.next = cur.next
cur.next.next = cur
cur.next = nxt
prev = cur
cur = nxt
return dummy.next
代码随想录这个图表把步骤写的很清楚
- 时间复杂度:O(n)
- 空间复杂度:O(1)
19. Remove nth node from the end of the list
这题nth node from end,那肯定要俩个指针了。一开始没有想明白怎么判断是nth node from end,看了以后想清楚了:让fast先move到nth + 1的位置(remove nth,那cur要在nth之前),俩个在一直往前,直到fast is None
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(0)
dummy.next = head
slow = dummy
fast = dummy
for i in range(n + 1):
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
- 时间复杂度: O(n)
- 空间复杂度: O(1)
160. intersection of two list
这个需要一个helper function去判断length,思想:判断俩个list的length,然后将他们变成同样长度,然后判断是否相等,返回
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
if headA is None or headB is None:
return None
lenA = self.getLen(headA)
lenB = self.getLen(headB)
if lenA > lenB:
while lenA != lenB:
headA = headA.next
lenA -= 1
else:
while lenA != lenB:
headB = headB.next
lenB -= 1
while headA != headB:
headA = headA.next
headB = headB.next
return headA
def getLen(self, head):
length = 1
cur = head.next
while cur:
cur = cur.next
length += 1
return length
- 时间复杂度:O(n + m)
- 空间复杂度:O(1)
142. List Cycle II
这道题是之前看到的一个非常巧妙的想法:还是一如既往的slow and fast pointer
如何判断开始位置:
fast 和 slow 相等时, slow 走了 a + b, fast 走了 a + 2b + c, 所以我们可以得知,a = c
所以当fast 和 slow相等时,重设置一个pointer从head走起,当他们在相遇时,此时既为cycle开始的地方
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return None
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
slow2 = head
while slow != slow2:
slow = slow.next
slow2 = slow2.next
return slow
return None
- 时间复杂度: O(n),快慢指针相遇前,指针走的次数小于链表长度,快慢指针相遇后,两个index指针走的次数也小于链表长度,总体为走的次数小于 2n
- 空间复杂度: O(1)