# Leetcode题解 - 部分中等难度算法题解（56、957、825、781、1324、816）

##### 957. N 天后的牢房

class Solution:
def prisonAfterNDays(self, cells, N: int):
vis = []
while 1:
if not N:
return cells
if cells in vis:
ind = vis.index(cells)
break
tcell = cells.copy()
for i in range(len(cells)):
if i == 0 or i == len(cells)-1:
tcell[i] = 0
continue
if cells[i-1] == cells[i+1]:
tcell[i] = 1
else:
tcell[i] = 0
vis.append(cells)
cells = tcell
N -= 1
vis = vis[ind:]
return vis[N % len(vis)]


##### 825. 适龄的朋友

from collections import Counter
class Solution:
def numFriendRequests(self, ages) -> int:
ages, res = sorted(Counter(ages).items(), key=lambda x: x[0]), 0
for i in range(len(ages)):
if ages[i][0] < 15:
continue
res += (ages[i][1] - 1) * ages[i][1]
for j in range(i):
if ages[j][0] <= (ages[i][0] * 0.5 + 7):
continue
else:
res += ages[i][1] * ages[j][1]
return res


##### 781. 森林中的兔子

"""

"""
import math
from collections import Counter
class Solution:
for num, times in ans.items():
if not num:
res += times
else:
if times <= num + 1:
res += num + 1
else:
t = math.ceil(times / (num + 1))
res += t * (num + 1)
return res


##### 1324. 竖直打印单词

class Solution:
def printVertically(self, s: str):
s = s.split(" ")
l = len(sorted(s, key=lambda x:-len(x))[0])
for i in range(len(s)):
s[i] = s[i] + (l - len(s[i])) * " "
res = []
for i in zip(*s):
i = ("".join(list(i))).rstrip()
res.append(i)
return res


##### 816. 模糊坐标

1. 不是‘0’也不是'0.'但以0开头的不合理
2. 以‘0’结尾的不合理
"""

"""
class Solution:
def ambiguousCoordinates(self, S: str):
def produce(string):
res = []
# 本身就是一个完整的数字
if len(str(int(string))) == len(string):
res = [string]
# 如果全是零直接返回
if set(string) == {'0'}:
return res
# 在不同的位置添加小数点
for i in range(1,len(string)):
t = string[:i]+"."+string[i:]
# 不是'0'也不是'0.'开头的，以'0'开头的都要删掉
if len(string[:i]) >= 2 and string[:i].startswith("0"):
continue
# '0'结尾的也删掉
if string[i:].endswith('0'):
continue
res.append(t)
return res
S, res, r = S[1:-1], [], []
# 分割字符串获取整数、小数部分
for i in range(1, len(S)):
res.append((S[:i], S[i:]))
for x, y in res:
px = produce(x)
py = produce(y)
for i in px:
for j in py:
r.append("("+i+", "+j+")")
return r


##### 56. 合并区间

class Solution:
def merge(self, intervals):
res = []
# 先排序
intervals = sorted(intervals)
# 记录拼接的首尾大小
s, e = intervals[0][0], intervals[0][1]
for x, y in intervals[1:]:
# 你的头大于我的尾部，不可能拼接的。重新开始一次拼接
if x > e:
res.append([s, e])
s, e = x, y
continue
# 可以拼接到一起，更新尾巴
if y > e:
e = y
if [s, e] not in res:
res.append([s, e])
return res

posted @ 2020-02-19 22:57  但是我拒绝  阅读(751)  评论(1编辑  收藏  举报