Skip to content

Commit

Permalink
Merge pull request neetcode-gh#668 from KC10201/215-Kth-Largest-Eleme…
Browse files Browse the repository at this point in the history
…nt-in-an-Array-refactor-Python-solution

215 kth largest element in an array: refactor python solution
  • Loading branch information
Ahmad-A0 authored Aug 5, 2022
2 parents c0e5c06 + 90797b0 commit b111c26
Showing 1 changed file with 40 additions and 18 deletions.
58 changes: 40 additions & 18 deletions python/215-Kth-Largest-Element-in-an-Array.py
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]

0 comments on commit b111c26

Please sign in to comment.