forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request neetcode-gh#668 from KC10201/215-Kth-Largest-Eleme…
…nt-in-an-Array-refactor-Python-solution 215 kth largest element in an array: refactor python solution
- Loading branch information
Showing
1 changed file
with
40 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,26 +1,48 @@ | ||
class Solution: | ||
# Solution: Sorting | ||
# Time Complexity: | ||
# - Best Case: O(n) | ||
# - Average Case: O(n*log(n)) | ||
# - Worst Case:O(n*log(n)) | ||
# Extra Space Complexity: O(n) | ||
class Solution1: | ||
def findKthLargest(self, nums: List[int], k: int) -> int: | ||
nums.sort() | ||
return nums[len(nums) - k] | ||
|
||
k = len(nums) - k | ||
|
||
def quickSelect(l, r): | ||
if l == r: | ||
return nums[l] | ||
|
||
pivot, p = nums[r], l | ||
for i in range(l, r): | ||
if nums[i] <= pivot: | ||
nums[p], nums[i] = nums[i], nums[p] | ||
p += 1 | ||
nums[p], nums[r] = nums[r], nums[p] | ||
|
||
if p > k: | ||
return quickSelect(l, p - 1) | ||
elif p < k: | ||
return quickSelect(p + 1, r) | ||
# Solution: QuickSelect | ||
# Time Complexity: | ||
# - Best Case: O(n) | ||
# - Average Case: O(n) | ||
# - Worst Case: O(n^2) | ||
# Extra Space Complexity: O(1) | ||
class Solution2: | ||
def partition(self, nums: List[int], left: int, right: int) -> int: | ||
pivot, fill = nums[right], left | ||
|
||
for i in range(left, right): | ||
if nums[i] <= pivot: | ||
nums[fill], nums[i] = nums[i], nums[fill] | ||
fill += 1 | ||
|
||
nums[fill], nums[right] = nums[right], nums[fill] | ||
|
||
return fill | ||
|
||
def findKthLargest(self, nums: List[int], k: int) -> int: | ||
k = len(nums) - k | ||
left, right = 0, len(nums) - 1 | ||
|
||
while left < right: | ||
pivot = self.partition(nums, left, right) | ||
|
||
if pivot < k: | ||
left = pivot + 1 | ||
elif pivot > k: | ||
right = pivot - 1 | ||
else: | ||
return nums[p] | ||
break | ||
|
||
return quickSelect(0, len(nums) - 1) | ||
return nums[k] | ||
|