leetcode.215.Kth Largest Element in an Array

来源:互联网 发布:bt下载软件for mac 编辑:程序博客网 时间:2024/06/13 05:20

Description

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.

sln1

用快速排序对输入数组进行排序,然后拿出输入数组的第numsSize - k个元素,则为第k大元素。该算法的时间复杂度为O(NlogN),空间复杂度为O(1)。
p.s. 这里直接使用python的内置排序函数对数组进行排序。该函数用到的排序算法为Timsort,Timsort的平均时间复杂度为O(NlogN),空间复杂度为O(N)。

class Solution(object):    def findKthLargest(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: int        """        nums = sorted(nums)        return nums[len(nums) - k]

sln2

用快速排序的思想,从数组中选择一个元素作为主元,将小于该主元的元素置于数组左端,大于该主元的元素置于数组右端。通分析主元在分组之后的位置与k的大小关系,判断第k大的数是在该主元分割得到的左子数组中,还是又子数组中,还是就是该主元本身。然后迭代进行上述步骤,最终得到第k大的数。该算法的最好时间复杂度为O(N),最差时间复杂度为O(N^2)。空间复杂度为O(1)。

int findKthLargest(int* nums, int numsSize, int k) {    int low = 0;    int high = numsSize - 1;    k = numsSize - k;    while (low < high) {        int n = seperate(nums, low, high);        if (n < k) {            low = n + 1;        } else if (n > k) {            high = n - 1;        } else {            break;        }    }    return nums[k];}int seperate(int* nums, int low, int high) {    int i = low, j = high + 1;    while (1) {        while (i < high && nums[++i] < nums[low]);        while (j > low && nums[--j] > nums[low]);        if (i >= j) break;        exchange(nums, i, j);    }    exchange(nums, low, j);    return j;}void exchange(int* nums, int a, int b) {    int tmp = nums[a];    nums[a] = nums[b];    nums[b] = tmp;}

最后,这种算法的时间复杂度对输入数组中元素的顺序关系密切。为了尽量避免出现最差复杂度的情况,我们可以在算法的开始,将数组打乱。这样做可以简单的一定程度上回避掉O(N^2)的情况。

0 0