文章目录
- [6016. Excel 表中某个范围内的单元格](https://leetcode-cn.com/problems/cells-in-a-range-on-an-excel-sheet/)
- [6017. 向数组中追加 K 个整数](https://leetcode-cn.com/problems/append-k-integers-with-minimal-sum/)
- [6018. 根据描述创建二叉树](https://leetcode-cn.com/problems/create-binary-tree-from-descriptions/)
- [6019. 替换数组中的非互质数](https://leetcode-cn.com/problems/replace-non-coprime-numbers-in-array/)
- 总结
6016. Excel 表中某个范围内的单元格
看数据范围,直接一行
class Solution:
def cellsInRange(self, s: str) -> List[str]:
return [chr(i)+str(j) for i in range(ord(s[0]),ord(s[3])+1) for j in range(int(s[1]),int(s[4])+1)]
6017. 向数组中追加 K 个整数
贪心,等差数列求和,三行解法👇
class Solution:
def minimalKSum(self, nums: List[int], k: int) -> int:
nums,res,last,pt = sorted(set(nums)),(1+k)*k//2,k,0
while pt < len(nums) and nums[pt] <= last:last,res,pt = last+1,res+last-nums[pt]+1,pt+1
return res
六弦爷两行题解👇
class Solution:
def minimalKSum(self, nums: List[int], k: int) -> int:
book, t = set(nums), count(k + 1)
return (1 + k) * k // 2 + sum(next(y for y in t if y not in book) - x for x in book if x <= k)
6018. 根据描述创建二叉树
集合+哈希,五行搞定
class Solution:
def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:
parients,children = set([t[0] for t in descriptions]),set([t[1] for t in descriptions])
root,nodes = list(parients-children)[0],{c:TreeNode(c) for c in parients|children}
for p, c, l in descriptions :
(nodes[p].left,nodes[p].right) = (nodes[c],nodes[p].right) if l==1 else (nodes[p].left,nodes[c])
return nodes[root]
6019. 替换数组中的非互质数
栈模拟,五行搞定
class Solution:
def replaceNonCoprimes(self, nums: List[int]) -> List[int]:
lcm,stack = lambda a,b:a*b // math.gcd(a,b),list()
for x in nums:
while stack and math.gcd(stack[-1], x) != 1:x,y = lcm(x,stack[-1]),stack.pop()
stack.append(x)
return stack