-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathkth.py
More file actions
74 lines (58 loc) · 1.85 KB
/
kth.py
File metadata and controls
74 lines (58 loc) · 1.85 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# 100 pass - Logic to sort only initially
# * Every add will be iterated across the k length array
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
# initialize stream we need to use in the function
# * We only require k elements from the start, sort once and add everything later
self.nums = sorted(nums, reverse=True)[:k]
self.k = k-1
def add(self, val):
"""
:type val: int
:rtype: int
"""
# Null criteria
if not self.nums:
self.nums = [val]
return val
i = 0
while i < len(self.nums) and self.nums[i] > val:
i += 1
self.nums = self.nums[:i] + [val] + self.nums[i:]
self.nums = self.nums[:self.k+1]
return self.nums[self.k]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
"""
# Pending -- time limit exceeded
# * Sorting everytime add is called doesnt make sense!
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.array = nums
self.k = k
self.value = 0
def add(self, val):
"""
:type val: int
:rtype: int
"""
# Time Limit Exceeded logic otherwise all passed
self.array.append(val)
if val > self.value or not self.value:
self.array = sorted(self.array)[::-1]
self.array = self.array[:self.k]
self.value = self.array[-1]
return self.value
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
"""