[LeetCode] Challenge log 215

215. Kth Largest Element in an Array

https://leetcode.com/problems/kth-largest-element-in-an-array/description/

  1. Use len(k)-array to save the largest k elements
  2. Through binary search insertion to keep the array sorted.

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.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Soulution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# binary search insertion
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if len(nums) == 1: return nums[0]
arr = []
for ele in nums:
if len(arr) == k:
if ele < arr[k-1]:
continue
elif ele >= arr[0]:
arr = [ele] + arr[:-1]
continue
arr = self.insert(arr, ele)
if len(arr) > k: arr = arr[:k]
return arr[k-1]

def insert(self, arr, ele):
if arr == []: return [ele]
p1 = 0
p2 = len(arr)-1
while p2 >= p1:
temp = (p1 + p2) // 2
if ele >= arr[temp]:
p2 = temp - 1
else:
p1 = temp + 1
# print(p1,p2,ele)
return arr[:p1] + [ele] + arr[p1:]
1
# use set
0%