Leetcode 刷题笔记 (sort)

本文分享了在LeetCode上解决一系列算法问题的技巧,包括使用随机pivot的快速排序(912题),双指针与选择排序的三色问题(75题),以及链表排序(21, 148题)。通过实例演示了快速排序的改进方法、桶排序在高频元素查找中的应用,以及合并两个有序链表的基本操作。
摘要由CSDN通过智能技术生成

idea:

quicksort: 随机取pivot 可以避免最坏情况

912. Sort an Array (medium) (quicksort)

https://leetcode.com/problems/sort-an-array/

class Solution:
    def sortArray(self, nums: List[int]) -> List[int]:
        def partition(nums, l ,r):
            i = l # 左index
            j = r # 右index
            rdn_pivotidx = random.randint(l,r)
            nums[l],nums[rdn_pivotidx] = nums[rdn_pivotidx], nums[l] #随机pivot 防止worst case
            pivot = nums[l]
            while i != j:
                while i < j and nums[j] > pivot:
                    j -= 1
                while i < j and nums[i] <= pivot:
                    i += 1
                if i < j:
                    nums[i],nums[j] = nums[j],nums[i]
            nums[l],nums[i] = nums[i],nums[l]
            return i 
        def quicksort(nums,l,r):
            if l > r:
                return 
            pivot_idx = partition(nums,l,r)
            quicksort(nums,l,pivot_idx - 1)
            quicksort(nums,pivot_idx + 1,r)
            return nums
        
        return quicksort(nums,0,len(nums) - 1)
        

215. Kth Largest Element in an Array(medium)

https://leetcode.com/problems/kth-largest-element-in-an-array/

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        def partition(nums,l,r):
            i = l
            j = r
            rdx_idx = random.randint(l,r)
            nums[rdx_idx],nums[l] = nums[l], nums[rdx_idx]
            pivot = nums[l]
            while i != j:
                while i < j and nums[j] > pivot:
                    j -= 1
                while i < j and nums[i] <= pivot:
                    i += 1
                if i < j:
                    nums[i],nums[j] = nums[j],nums[i]
            nums[l],nums[i] = nums[i],nums[l]
            return i
        def qs(nums,l,r):
            if l > r:
                return
            pivot_idx = partition(nums,l,r)
            qs(nums,l,pivot_idx-1)
            qs(nums,pivot_idx+1,r)
            return nums
        nums = qs(nums,0,len(nums)-1)
        return nums[len(nums)-k]

75. Sort Colors (medium) (double pointers & selection sort)

三指针:

https://leetcode.com/problems/sort-colors/

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        l = 0
        r = len(nums) - 1
        cur = 0
        while cur <= r:
            if nums[cur] == 0:
                nums[cur],nums[l] = nums[l],nums[cur]
                l += 1
                cur += 1
            elif nums[cur] == 2:
                nums[cur],nums[r] = nums[r],nums[cur]
                r -= 1
            else:
                cur += 1
            
        

nums[cur] == 2时, 交换nums[cur],nums[r] 换回来的cur还未判断,不需要cur++

桶排序:

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        buckets = [0, 0, 0]
        for num in nums:
            buckets[num] += 1
        start = 0
        for idx, val in enumerate(buckets):  # get idx, val
            for i in range(start,start+val):
                nums[i] = idx
            start = start + val

桶排序题:347, 451, 75

347. Top K Frequent Elements(medium) (Bucker sort)

桶排序:hashmap
用一个字典存储对应数量
https://leetcode.com/problems/top-k-frequent-elements/

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        dict = {}
        for key in nums:
            if key not in dict:
                dict[key] = 0
            dict[key] += 1
        rst = sorted(dict, key = dict.get, reverse = True)
        return rst[:k]

451. Sort Characters By Frequency(medium)

https://leetcode.com/problems/sort-characters-by-frequency/

class Solution:
    def frequencySort(self, s: str) -> str:
        dict = {}
        for i in range(len(s)):
            if s[i] not in dict:
                dict[s[i]] = 0
            dict[s[i]] += 1
        arr = sorted(dict.items(), key=lambda x:x[1], reverse = True)
        rst = ''
        for k,v in arr:
            rst += k*v
        return rst
        

21. Merge Two Sorted Lists (Easy 链表排序)

https://leetcode-cn.com/problems/merge-two-sorted-lists/

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        dummy_head = ListNode(0)
        tmp, tmp_1, tmp_2 = dummy_head, list1, list2
        while tmp_1 and tmp_2:
            if tmp_1.val <= tmp_2.val:
                tmp.next = tmp_1
                tmp_1 = tmp_1.next
            else:
                tmp.next = tmp_2
                tmp_2 = tmp_2.next
            tmp = tmp.next
        if tmp_1:
            tmp.next = tmp_1
        if tmp_2:
            tmp.next = tmp_2
        return dummy_head.next


148 Sort List(medium 归并排序+快慢指针)

https://leetcode-cn.com/problems/sort-list/

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        def sortfun(head:ListNode, tail:ListNode) -> Optional[ListNode]:
            if not head:
                return head
            if head.next == tail:
                head.next = None
                return head
            fast,slow = head, head
            while fast != tail:
                fast = fast.next
                slow = slow.next
                if fast != tail:
                    fast = fast.next
            mid = slow 
            return merge(sortfun(head, mid), sortfun(mid, tail))

        def merge(head:ListNode, tail:ListNode):
            dummy_head = ListNode(0)
            tmp, tmp_1, tmp_2 = dummy_head, head, tail
            while tmp_1 and tmp_2:
                if tmp_1.val <= tmp_2.val:
                    tmp.next = tmp_1
                    tmp_1 = tmp_1.next
                else:
                    tmp.next = tmp_2
                    tmp_2 = tmp_2.next
                tmp = tmp.next
            if tmp_1:
                tmp.next = tmp_1
            if tmp_2:
                tmp.next = tmp_2
            return dummy_head.next
        return sortfun(head, None)

56. Merge Intervals(medium 区间合并)

https://leetcode-cn.com/problems/merge-intervals/

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        intervals = sorted(intervals, key = lambda x:x[0])
        merged = []
        for interval in intervals:
            if not merged or merged[-1][1] < interval[0]:
                merged.append(interval)
            else:
                merged[-1][1] = max(merged[-1][1],interval[1])
        return merged

sorted(x, key = lambda a:a[0]/[1], reverse=T/F)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值