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)的情况。
- Leetcode Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- [LeetCode] Kth Largest Element in an Array
- [leetcode] Kth Largest Element in an Array
- leetcode--Kth Largest Element in an Array
- #leetcode#Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- 【Leetcode】Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- Kth Largest Element in an Array -- leetcode
- [Leetcode]Kth Largest Element in an Array
- [LeetCode]Kth Largest Element in an Array
- *LeetCode-Kth Largest Element in an Array
- LeetCode----Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- leetcode-Kth Largest Element in an Array
- LeetCode -- Kth Largest Element in an Array
- 微信小程序之仿android fragment之可滑动的底部导航栏实例 —— 微信小程序实战系列(4)
- Linux内核分析 X86汇编基础测验
- Linux基本概念及操作
- struts 1 和 struts 2区别,struts 2创建
- 2017已来,最全面试总结——这些Android面试题你一定需要
- leetcode.215.Kth Largest Element in an Array
- U3D的坑--CommandInvokationFailure: Failed to re-package resources.
- 图片水平滚动,当鼠标悬停的时候暂停滚动
- Kali 64位 安装32位库并编译程序
- Sqlmap使用指南(二)
- Jquery——Day9(折叠菜单)
- springmvc进行Json数据交互
- JavaScript—迭代器和生成器
- CentOS6.7_MYSQL_yum安装xtrabackup