Skip to content

Commit 138947d

Browse files
committed
no message
1 parent b9c2a70 commit 138947d

File tree

2 files changed

+51
-29
lines changed

2 files changed

+51
-29
lines changed

common/heap-sort.py

Lines changed: 27 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,33 @@
1+
#O(LogN), used when part of the array is already heapified.
2+
def heapify(A, N, i):
3+
largest = i
4+
l = i*2+1
5+
r = i*2+2
6+
7+
if l<N and A[l]>A[largest]: largest = l
8+
if r<N and A[r]>A[largest]: largest = r
9+
if largest!=i:
10+
A[largest], A[i] = A[i], A[largest]
11+
heapify(A, N, largest)
12+
13+
#O(NLogN)
114
def heapSort(A):
2-
#build max heap
3-
def heapify(A, n, i):
4-
if i>=n: return
5-
l, r = i*2+1, i*2+2
6-
left = A[l] if l<n else float('-inf')
7-
right = A[r] if r<n else float('-inf')
8-
9-
if left>A[i] or right>A[i]:
10-
if left>right:
11-
A[i], A[l] = A[l], A[i]
12-
heapify(A, n, l)
13-
else:
14-
A[i], A[r] = A[r], A[i]
15-
heapify(A, n, r)
16-
17-
n = len(A)
18-
19-
for i in reversed(xrange(n)):
20-
heapify(A, n, i)
21-
22-
for i in reversed(xrange(1, n)):
23-
A[i], A[0] = A[0], A[i]
15+
N = len(A)
16+
17+
#build max heap, O(NLogN). Can be optimized to the O(N).
18+
for i in range(N//2-1, -1, -1):
19+
heapify(A, N, i)
20+
21+
#keep swapping the largest
22+
for i in range(N-1, -1, -1):
23+
A[0], A[i] = A[i], A[0]
2424
heapify(A, i, 0)
2525

2626

27-
28-
A = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
27+
A = [12, 11, 13, 5, 6, 7]
2928
heapSort(A)
30-
print A
29+
print(A)
3130

32-
"""
33-
Time Complexity O(NLogN) in best, average, worst case.
34-
Space Complexity O(1)
35-
"""
31+
A = [1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17]
32+
heapSort(A)
33+
print(A)

problems/python3/3sum-closest.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""
2+
Time: O(N^2)
3+
Space: O(1)
4+
"""
5+
class Solution:
6+
def threeSumClosest(self, nums: List[int], target: int) -> int:
7+
nums.sort()
8+
9+
N = len(nums)
10+
ans = float('inf')
11+
12+
for i in range(N):
13+
j = i+1
14+
k = N-1
15+
16+
while j<k:
17+
total = nums[i]+nums[j]+nums[k]
18+
if total==target: return total
19+
if abs(target-ans)>abs(target-total): ans = total
20+
if total>target:
21+
k -= 1
22+
elif total<target:
23+
j += 1
24+
return ans

0 commit comments

Comments
 (0)