数组中的第 k 大的数字
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
n = len(nums)
def partitions(arr, l, r):
base = arr[l]
while l < r:
while l < r and arr[r] > base:
r -= 1
arr[l] = arr[r]
while l < r and arr[l] <= base:
l += 1
arr[r] = arr[l]
arr[l] = base
return l
def qulick_sort(nums, l,r):
mid = partitions(nums, l, r)
if mid == n - k:
return nums[mid]
elif mid < (n - k):
return qulick_sort(nums, mid + 1, r)
else:
return qulick_sort(nums, l, mid - 1)
return qulick_sort(nums, 0, n - 1)
易错总结
33. 搜索旋转排序数组【旋转数组找k大】
class Solution:
def search(self, nums: List[int], target: int) -> int:
n = len(nums)
l, r = 0, n - 1
while l <= r:
mid = (l + r) // 2
base = nums[mid]
if target == base:
return mid
elif nums[0] <= base:
if nums[0] <= target < base:
r = mid - 1
else:
l = mid + 1
else:
if base < target <= nums[-1]:
l = mid + 1
else:
r = mid - 1
return -1
易错总结
347. 前 K 个高频元素
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
import heapq
dic = {}
for num in nums:
if num not in dic:
dic[num] = 1
else:
dic[num] += 1
heap = []
for key, val in dic.items():
if len(heap) >= k:
if val > heap[0][0]:
heapq.heappop(heap)
heapq.heappush(heap, (val, key))
else:
heapq.heappush(heap, (val, key))
return [item[1] for item in heap]
易错总结
23.合并k个升序链表
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
import heapq
heap = []
dummy = ListNode(0)
cur = dummy
for index, l in enumerate(lists):
if l:
heapq.heappush(heap, (l.val, index, l))
while heap:
val, index, l = heapq.heappop(heap)
cur.next = l
cur = cur.next
if l.next:
l = l.next
heapq.heappush(heap, (l.val, index, l))
return dummy.next
易错总结
链表反转
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre = None
cur = head
while cur:
nex = cur.next
cur.next = pre
pre = cur
cur = nex
return pre
易错总结
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0, head)
pre = dummy
while pre.next and pre.next.next:
cur = pre.next
nex = pre.next.next
cur.next = nex.next
nex.next = cur
pre.next = nex
pre = pre.next.next
return dummy.next
易错总结