Skip to content

Commit 79f6649

Browse files
authored
Create find-the-kth-largest-integer-in-the-array.py
1 parent 0790500 commit 79f6649

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Time: O(n) ~ O(n^2), O(n) on average
2+
# Space: O(1)
3+
4+
import random
5+
6+
7+
class Solution(object):
8+
def kthLargestNumber(self, nums, k):
9+
"""
10+
:type nums: List[str]
11+
:type k: int
12+
:rtype: str
13+
"""
14+
def nth_element(nums, n, compare=lambda a, b: a < b):
15+
def tri_partition(nums, left, right, target, compare):
16+
mid = left
17+
while mid <= right:
18+
if nums[mid] == target:
19+
mid += 1
20+
elif compare(nums[mid], target):
21+
nums[left], nums[mid] = nums[mid], nums[left]
22+
left += 1
23+
mid += 1
24+
else:
25+
nums[mid], nums[right] = nums[right], nums[mid]
26+
right -= 1
27+
return left, right
28+
29+
left, right = 0, len(nums)-1
30+
while left <= right:
31+
pivot_idx = random.randint(left, right)
32+
pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)
33+
if pivot_left <= n <= pivot_right:
34+
return
35+
elif pivot_left > n:
36+
right = pivot_left-1
37+
else: # pivot_right < n.
38+
left = pivot_right+1
39+
40+
nth_element(nums, k-1, compare=lambda a, b: a > b if len(a) == len(b) else len(a) > len(b))
41+
return nums[k-1]

0 commit comments

Comments
 (0)