[diary of dishes] 215 The kth largest element in the array

Posted by krang on Tue, 18 Jan 2022 23:24:07 +0100

Series index: [diary of dishes] the days when LeetCode used Python to abuse

The road of cultivating immortality with vegetables and chickens -- January 17, 2022
Although I haven't written a topic solution blog these two days, I still haven't broken one day. I just write simple questions and sometimes I don't think it's necessary to write them.

[title]

Given the integer array nums and integer k, please return the K largest element in the array.

Note that you need to find the K largest element after the array is sorted, not the k different element.

  • Tags: array, heap sort
  • Difficulty: medium
Example 1:
input: [3,2,1,5,6,4] and k = 2
 output: 5

Example 2:
input: [3,2,3,1,2,4,5,5,6] and k = 4
 output: 4

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

[my code]

This efficiency is really.. Python is not as efficient as c in terms of algorithm, and my level is not high, so I'd better take a look at the code learning of the big guys, but it's a little too much to use sort directly. / wul

It is mainly the idea of selection and sorting.

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        for i in range(len(nums)-1, len(nums)-1-k, -1):
            m = i
            for j in range(i-1, -1, -1):
                if nums[j] > nums[m]:
                    m = j
            if m != i:
                nums[i], nums[m] = nums[m], nums[i]
        return nums[-k]

[reference code 1] violence act

I have to say that the efficiency of direct sort is much higher than what I wrote.

Simple two lines to finish directly, NB (although I can't exercise the knowledge of data structure) if I write this in the interview, will it

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        nums.sort()
        return nums[-k]

[reference code 2] heap sorting

The idea of ascending heap sorting is as follows:

  1. First establish the large top reactor

  2. Let the maximum element of the pile top be exchanged with the last one, then adjust the first element to the last second elements, and this step gets the maximum value.

  3. Then exchange the top and bottom second elements, then adjust the first element to the third elements, and this step gets second values.

  4. And so on until the last element is exchanged.

In this problem, we only need to establish a large top pile once and adjust k-1 to get the k-th largest number.

Time complexity: O(n2)

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        # Adjust to large top pile
        def heapify(nums, index, end):
            left = index * 2 + 1
            right = left + 1
            while left <= end:
                # The current node is a non leaf node
                max_index = index
                if nums[left] > nums[max_index]:
                    max_index = left
                if right <= end and nums[right] > nums[max_index]:
                    max_index = right
                if index == max_index:
                    # If the exchange is not used, it indicates that the exchange has ended
                    break
                nums[index], nums[max_index] = nums[max_index], nums[index]
                # Continue adjusting subtree
                index = max_index
                left = index * 2 + 1
                right = left + 1
                
        # Initialize large top heap
        def buildMaxHeap(nums):
            size = len(nums)
            # (size-2) // 2 is the last non leaf node. Leaf nodes need not be adjusted
            for i in range((size - 2) // 2, -1, -1):
                heapify(nums, i, size - 1)
            return nums

        buildMaxHeap(nums)
        size = len(nums)
        for i in range(k-1):
            nums[0], nums[size-i-1] = nums[size-i-1], nums[0]
            heapify(nums, 0, size-i-2)
        return nums[0]
        

[reference code 3] quick sort

Each adjustment of quick sort will determine the final position of an element, and take the element as the boundary to divide the array into two arrays. The former array element is smaller than the element, and the latter element is larger than the element.

In this way, the answer is found as long as the element of a partition happens to be the k-th subscript. And we only need to pay attention to the sorting of the interval where the K element is located, and the interval sorting irrelevant to the K element can be ignored. This further reduces the number of execution steps.

import random
class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        def randomPartition(nums, low, high):
            i = random.randint(low, high)
            nums[i], nums[high] = nums[high], nums[i]
            return partition(nums, low, high)

        def partition(nums, low, high):
            x = nums[high]
            i = low-1
            for j in range(low, high):
                if nums[j] <= nums[high]:
                    i += 1
                    nums[i], nums[j] = nums[j], nums[i]
            nums[i+1], nums[high] = nums[high], nums[i+1]
            return i+1

        def quickSort(nums, low, high, k):
            n = len(nums)
            if low < high:
                pi = randomPartition(nums, low, high)
                if pi == n-k:
                    return nums[len(nums)-k]
                if pi > n-k:
                    quickSort(nums, low, pi-1, k)
                if pi < n-k:
                    quickSort(nums, pi+1, high, k)

            return nums[len(nums)-k]

        return quickSort(nums, 0, len(nums)-1, k)
        

[thinking]

A song "tomorrow song" is given to you, and I hope I can cherish the present!

Tomorrow after tomorrow, how many tomorrow.
Tomorrow never comes.
The world is tired by tomorrow. Spring and autumn come, and the veteran comes.
The water flows eastward in the morning and the sun falls in the West in the evening.
How can a hundred years tomorrow be? Please listen to my tomorrow song.
Tomorrow after tomorrow, how many tomorrow!
Wait for tomorrow, everything is wasted.
The world is tired by tomorrow. Tomorrow is endless.
In the morning and dusk, the water flows to the East, and the long day falls to the West in ancient times.
How can a hundred years tomorrow be? Please listen to my tomorrow song.

Topics: Algorithm leetcode