731. My Calendar II
overlap的部分放重复的,只要检查overlap。
class MyCalendarTwo(object):
# O(N)
def __init__(self):
self.overlap = []
self.nums = []
def book(self, start, end):
for s, e in self.overlap:
if start < e and end > s:
return False
for s, e in self.nums:
if start < e and end > s:
self.overlap.append([max(start, s), min(end, e)])
self.nums.append([start, end])
return True
36. Valid Sudoku
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
return self.isRowValid(board) and self.isColValid(board) and self.isBoxValid(board)
def isValidUnit(self, unit):
unit = [x for x in unit if x != '.']
return len(unit) == len(set(unit))
def isRowValid(self, board):
for r in board:
if not self.isValidUnit(r):
return False
return True
def isColValid(self, board):
for c in zip(*board):
if not self.isValidUnit(c):
return False
return True
def isBoxValid(self, board):
for i in (0, 3, 6):
for j in (0, 3, 6):
box = [board[r][c] for r in xrange(i, i+3) for c in xrange(j, j+3)]
if not self.isValidUnit(box):
return False
return True
621. Task Scheduler
class Solution(object):
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
counter = collections.Counter(tasks)
task_list = [[value, key] for key, value in counter.items()]
task_list.sort(reverse=True)
most = task_list[0][0]
sameLength = sum([1 for value, key in task_list if value == most])
return max((most-1) * (n+1) + sameLength, len(tasks))
158. Read N Characters Given Read4 II - Call multiple times
什么神经病题目,理解不了
# The read4 API is already defined for you.
# @param buf, a list of characters
# @return an integer
# def read4(buf):
class Solution(object):
def __init__(self):
self.queue = []
def read(self, buf, n):
"""
:type buf: Destination buffer (List[str])
:type n: Maximum number of characters to read (int)
:rtype: The number of characters read (int)
"""
num = 0
while True:
buf4 = [''] * 4
size = read4(buf4)
self.queue += buf4
minSize = min(len(self.queue), n-num)
if minSize == 0:
break
for i in xrange(minSize):
buf[num] = self.queue.pop(0)
num += 1
return num
398. Random Pick Index
不需要sorted的,后面每次遇到的3,可以替换第一个3的概率是 1/count,如果正好random是这个概率 ,就替换3.
class Solution(object):
def __init__(self, nums):
self.nums = nums
def pick(self, target)
re = -1
count = 0
for i, n in enumerate(self.nums):
if target == n:
count += 1
if random.randint(1, count) == 1:
re = i
return re