leetcode 騰訊精選50題 21

2021-09-27 03:16:00 字數 720 閱讀 4426

given a linked list, rotate the list to the right by k places, where k is non-negative.

鍊錶的特殊性在於其可以只改變其所指向的位址,而不改變資料存放的真正位址,於是將其收尾閉合後可直接得到乙個閉環的鍊錶,在將其在指定的位置斷開即可,指定的位置為n-k%n,新的段頭為n-k%n,段位為n-k%n-1

class solution:

def rotateright(self, head: listnode, k: int) -> listnode:

if not head:

return none

if not head.next:

return head

old_tail = head

n = 1

while old_tail.next:

old_tail = old_tail.next

n += 1

old_tail.next = head

new_tail = head

for i in range(n - k % n - 1):

new_tail = new_tail.next

new_head = new_tail.next

new_tail.next = none

return new_head

leetcode騰訊精選50題(1)

菜鳥第一課 給定乙個排序陣列,你需要在原地刪除重複出現的元素,使得每個元素只出現一次,返回移除後陣列的新長度。不要使用額外的陣列空間,你必須在原地修改輸入陣列並在使用 o 1 額外空間的條件下完成。示例 1 給定陣列 nums 1,1,2 函式應該返回新的長度 2,並且原陣列 nums 的前兩個元素...

leetcode 騰訊精選50題 LRU快取機制

題目如下 運用你所掌握的資料結構,設計和實現乙個 lru 最近最少使用 快取機制。它應該支援以下操作 獲取資料 get 和 寫入資料 put 獲取資料 get key 如果金鑰 key 存在於快取中,則獲取金鑰的值 總是正數 否則返回 1。寫入資料 put key,value 如果金鑰不存在,則寫入...

騰訊精選50題(1)

155.最小棧 設計乙個支援push,pop,top操作,並能在常數時間內檢索到最小元素的棧。示例 minstack minstack new minstack minstack.push 2 minstack.push 0 minstack.push 3 minstack.getmin 返回 3....