Skip to content

Commit 2d438e1

Browse files
committed
no message
1 parent 42ded99 commit 2d438e1

File tree

2 files changed

+69
-2
lines changed

2 files changed

+69
-2
lines changed

problems/kth-largest-element-in-an-array.py

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,5 +40,27 @@ def findKthLargest(self, nums, k):
4040
"""
4141
class Solution(object):
4242
def findKthLargest(self, nums, k):
43-
#to be continued...
44-
pass
43+
def sortRange(A, l, r):
44+
if l>=r: return A
45+
46+
p = A[(l+r)/2]
47+
i = partition(A, l, r, p)
48+
if k<i:
49+
sortRange(A, l, i-1)
50+
else:
51+
sortRange(A, i, r)
52+
return A
53+
54+
def partition(A, l, r, p):
55+
while l<=r:
56+
while A[l]<p: l += 1
57+
while A[r]>p: r -= 1
58+
if l<=r:
59+
A[l], A[r] = A[r], A[l]
60+
l += 1
61+
r -= 1
62+
return l
63+
64+
k = len(nums)-k #redefine the problem to find the kth nums when sorted
65+
sortRange(nums, 0, len(nums)-1)
66+
return nums[k]

problems/sort-colors.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution(object):
2+
def sortColors(self, nums):
3+
l = 0
4+
r = len(nums)-1
5+
6+
i = 0
7+
while i<=r:
8+
if nums[i]==0:
9+
nums[l], nums[i] = nums[i], nums[l]
10+
l += 1
11+
i += 1
12+
elif nums[i]==2:
13+
nums[i], nums[r] = nums[r], nums[i]
14+
r -= 1
15+
elif nums[i]==1:
16+
i += 1
17+
18+
# counting sort
19+
class Solution(object):
20+
def sortColors(self, nums):
21+
count0 = count1 = count2 = 0
22+
23+
for num in nums:
24+
if num==0:
25+
count0 += 1
26+
elif num==1:
27+
count1 += 1
28+
elif num==2:
29+
count2 += 1
30+
31+
i = 0
32+
while count0>0:
33+
nums[i] = 0
34+
i += 1
35+
count0 -= 1
36+
37+
while count1>0:
38+
nums[i] = 1
39+
i += 1
40+
count1 -= 1
41+
42+
while count2>0:
43+
nums[i] = 2
44+
i += 1
45+
count2 -= 1

0 commit comments

Comments
 (0)