Skip to content

Instantly share code, notes, and snippets.

Avatar

Ray liyunrui

  • Singapore
View GitHub Profile
View 295. Find Median from Data Stream.py
class MedianFinder:
"""
Binary Search + Insert
T: O(logn) +O(n) = O(n) for add function O(1) for findMedian.
S: O(n)
我們用一個array不斷存放新進來的data, as time goes, it's become inefficient in terms of space(not scalable)
Two heaps: max heap+min_heap+balance
T: 3*O(logn) for add function O(1) for findMedian.
S: O(n)
View 703. Kth Largest Element in a Stream.py
class KthLargest:
"""
Binary Search+ Insert
[2,4,5,8]
k=3
add 3 -> [2,3,4,5,8]-->return 4
-
add 4 -> [2,3,4,5,5,8]-->return 5
-
[2,3,4,5,5,8,10]
View 1221. Split a String in Balanced Strings.py
class Solution:
def balancedStringSplit(self, s: str) -> int:
balance = 0
n = len(s)
ans = 0
for i in range(n):
if s[i] == "R":
balance+=1
else:
balance-=1
View 451. Sort Characters By Frequency.py
class Solution:
"""
what's distribution of input string s:
---> s consists of English letters and digits. At most, 26+10 numbers
Heap solution and Sorting takes O(nlogn)
Bucket sort
freq array=[0,1,2,3,..,max_freq]
@liyunrui
liyunrui / bucketSort.py
Last active Jul 8, 2021
leetcode-sorting
View bucketSort.py
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
return self.bucketSort(nums)
def bucketSort(self, A):
"""
1. It's in-place sorting.
2. Bucket sort is mainly useful when input is uniformly distributed over a range.(floating number is allowed)
step1: create n buckets
step2: put element into buckets
View 692. Top K Frequent Words.py
class Solution:
"""
{
i:2
love:2
leetcode:1
codong:1
}
怎麼處理k=1
heqp可能會丟掉i而不是丟掉love
View 215. Kth Largest Element in an Array.py
class Solution:
"""
Thought Process:
Sorting
PQ:
if k == n:
we return min elememnt
So we use a pq with size k to maintain a top k elements out of n.
after looping over all elements in the given array. Return the topmost one, the smallest one inside the pq with size k, which is kth largest elememnt
View binary_tree_traversal.py
"""
Given a bst
5
/ \
3 7
/ \ /
1 4 6
pre-order: 5-> 3 -> 7 ==> 5->3->1->4->7->6
/ \ /
1 4 6
@liyunrui
liyunrui / insertionSort.py
Last active May 9, 2021
leetcode-sorting
View insertionSort.py
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
return self.insertionSort(nums)
def insertionSort(self, A):
"""
思路:
i這個指針的元素代表我們需要插入的元素, 經過一輪處理後我們希望i的左邊是partial sorted的.
所以當i走到最後, 整個arraysort完.
為了做到這部, 每次都create 一個指針ji開始遞減到index 0.每一次遞減都跟上一個元素比如果比較大就交換.
View 48. Rotate Image.py
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
m = len(matrix)
n = len(matrix[0])
row_b = 0 # 0-> 1
row_e = m-1 # 2->1
col_b = 0