February-215. The kth largest element in the array & smallest heap

 

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        #直接排序,然后找到第k个最大的元素
        nums_res = sorted(nums,reverse=True)
        return nums_res[k-1]


        #构建一个大小为k的最小堆,堆顶元素就是第k个最大的元素
        heap = nums
        heapq.heapify(heap)

        while len(heap)>k:
            heapq.heappop(heap)
        
        return heap[0]

 

 

 

class Solution:
    def thirdMax(self, nums: List[int]) -> int:
        if len(set(nums))<3:
            return max(nums)
        
        #最小堆:插入时间复杂度是log(n)
        heap = list(set(nums))
        heapq.heapify(heap)
 
        while len(heap)>3:
            heapq.heappop(heap)
        
        return heap[0]

        #排序
        nums = list(set(nums))
        nums_res = sorted(nums,reverse=True)
        return nums_res[2]

        #O(n)时间复杂度
        nums = set(nums)
        n = len(nums)
        if n < 3:
            return max(nums)
        max1 = max(nums)
        nums.remove(max1)
        max2 = max(nums)
        nums.remove(max2)

        return max(nums)

The first two do not satisfy O(n) time complexity, and only the last one satisfies O(n) time complexity.

 

class Solution:
    def topKFrequent(self, words: List[str], k: int) -> List[str]:
        
        #堆操作
        #时间复杂度:O(Nlogk)
        num_dic = dict(Counter(words))
        import heapq  
        h = []
        res = []
        for key, value in num_dic.items():
            heapq.heappush(h, (-value, key))  # 按第一个键值进行排序,堆顶是最小值,如果第一个元素相同那就按照第二个元素进行排序
        
        for _ in range(k):
            res.append(heapq.heappop(h)[1])
        
        return res
        



        
        #时间复杂度:O(NlogN)
        count = collections.Counter(words)
        candidates = count.keys()
        #先按照value进行排序,如果value排序相同,在按照key进行排序
        candidates = sorted(candidates,key = lambda x:(-count[x],x))
        return candidates[:k]
        

This problem is troublesome. When it is required to have the same frequency, it needs to be sorted in alphabetical order, so we still use two methods; ① dictionary + sort; ② minimum heap.

  • Dictionary + sort
    • Use hash table to count the number of occurrences of each word
    • Take out the key and sort in ascending order. The sentence of sorting is that the value is negative. If the value is the same, it will be sorted by word
    • Finally return the first k elements, because we added a negative sign to the value, the maximum value before adding the negative becomes the minimum value, so return the first k elements
  • Minimum heap
    • Construct a minimum heap, according to -value, if the value is the same, then we will sort according to the second element
    • Then pop the k elements at the top of the stack. These k elements are the three most frequently occurring elements

 

 

class Solution:
    def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
        

        #直接排序法
        points.sort(key=lambda x: (x[0] ** 2 + x[1] ** 2))
        return points[:K]



        #建一个最小堆,然后不断的堆顶的元素。
        distance = []
        for i in range(len(points)):
            x,y = points[i][0],points[i][1]
            distance.append(x*x+y*y)
        dic = defaultdict(int)
        #字典的key是index,value是点到原点之间的距离
        for i in range(len(distance)):
            dic[i]= distance[i]
        heap = []
        res = []
        for key,value in dic.items():
            heapq.heappush(heap,(value,key))
           
        for _ in range(K):
            index = heapq.heappop(heap)[1]
            res.append(points[index])

       

        return res
  • Direct ordering
    • Calculate the distance, sort directly, and then select the first k elements
  • Build minimum heap method
    • Calculate the distance first
    • Then build a dictionary, key is index, value is distance
    • Then build the smallest heap, and take out k elements from the top of the smallest heap.
    • The k elements taken out are just the index, and then take out the coordinates in the list according to the index.

 Summary: A simple application of the smallest heap.

 

Guess you like

Origin blog.csdn.net/weixin_37724529/article/details/113843215