LC204. Count Primes

optimal: Sieve of Eratosthenes class Solution: # O(N*lglgN) class Solution: def countPrimes(self, n: int) -> int: if n < 2: return 0 res = [True] * n res[0] = res[1] = False # 0 and 1 is not prime here for i in range(2,int(n**0.5)+1): if res[i]: for j in range(i*i,n,i):... [Read More]
Tags: Math HashTable

LC1041 Robot Bounded In Circle

class Solution: def isRobotBounded(self, instructions: str) -> bool: # time O(N) space O(1) #step1 initialize clockwise direction momentum changes, start point, momentum pointer dirs = [(0,1),[1,0],(0,-1),(-1,0)] x,y = 0,0 i = 0 #face north, so dx,dy = 0, 1 => i = 1 # step2: iterate instructions for ins in... [Read More]
Tags: Array Stack

LC1094 Car Pooling

from heapq import heappush, heappop class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: if not trips: return False pq = [] for pp, start, end in trips: heappush(pq,(start,pp)) heappush(pq,(end,-pp)) while pq: capacity -= heappop(pq)[1] if capacity < 0: return False return True [Read More]
Tags: String

Wood Cut

question class Solution: """ @param L: Given n pieces of wood with length L[i] @param k: An integer @return: The maximum length of the small pieces """ def woodCut(self, L, k): if sum(L)<k or not L: return 0 l = 1 r = max(L) size = len(L) while l <=... [Read More]