(Mid) 24. 两两交换链表中的节点
注意:创建两个变量temp 和temp1来储存要交换的两个点的值
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummyHead = ListNode(0, next = head)
cur = dummyHead
while(cur.next and cur.next.next):
# 这里需要有一个temp 来储存cur.next 的值,
# 因为cur.next = cur.next.next会把中途的链接弄断
temp = cur.next
temp1 = cur.next.next.next
cur.next = cur.next.next #dummyhead.next = 2
cur.next.next = temp #cur.next 已经变成2了, 然后2.next= temp -> 2.next = 1
temp.next = temp1
cur = cur.next.next
return dummyHead.next
(Mid) 19. 删除链表倒数第N个节点
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
# 创建一个dummyHead, dummyHead.next是原来的linked List 的head
dummyHead = ListNode(0, next = head)
# slow和fast都从dummyHead开始
slow = dummyHead
fast = dummyHead
# 快指针先开始移动n+1个位置, 因为这样才能当快指针移动到null的时候,
# 慢指针刚好停在n-1的位置上
for i in range(n+1):
print(i)
fast = fast.next
# 当fast移动到最后一位None的时候, slow刚好到n-1 的位置
while(fast != None):
slow = slow.next
fast = fast.next
# 将slow.next = slow.next.next 跳过中间的nth node
slow.next = slow.next.next
return dummyHead.next
(Easy)141. 环形链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
# 设置slow 和 fast 指针从head开始, fast比slow快一步,
# 然后如果有环的话, fast和slow 终会相遇的
slow = head
fast = head
while(fast != None and fast.next != None):
slow = slow.next
fast = fast.next.next
if(fast == slow):
return True
return False
(Easy)1356. Sort Integers by the Number of 1 Bits
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
# 总的 time complexity = O(n * log(n))
dic = {} # dict中储存的是key
for n in arr:
count = 0
temp = n
while n != 0:
# print('bfr n =', n)
remainder = n % 2
if remainder == 1:
count += 1
# print('re', remainder, 'count', count)
n = n // 2
# print('aft diving by 2 n = ', n)
if count in dic:
dic[count].append(temp) # key 为count, value = [拥有相同count的数字]
else:
dic[count] = [temp]
dic[count].sort() # 对于key中value数组内部自己排序,ascending order
# 然后根据外面的key排序
hashmap_sorted = dict(sorted(dic.items()))
res = []
for n in hashmap_sorted.values():
res.extend(n)
return res
(Mid)142. 环形链表II
明天继续