Problem
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.
从无序数组中找出并返回第k大的数
Example
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.
# 思路一
对整个数组排序,复杂度至少为nlogn
# 思路二
建立数组保存最大的k个值,当数组更新时需要重新排序
def findKthLargest(nums, k):
cur = 0
for i in range(1,len(nums)):
cur = nums[i]
if cur > nums[i-1]: # 不是末尾元素则查找插入位置,否则不需要改动
j = i-1
while j >= 0:
if cur > nums[j]:
nums[j+1] = nums[j] # 当前数组向右移动
j -= 1
else:break
nums[j+1] = cur
return nums[k-1]
其它方法,和703题一起,明天继续。需要时间理解一下快排和堆