继续leetcode刷题生涯
这里记录的都是笔者觉得有点意思的做法
参考了好几位大佬的题解,尤其是powcai大佬和labuladong大佬,感谢各位大佬
# 26进制转10进制
class Solution:
def titleToNumber(self, s: str) -> int:
res = 0
bit = 1
for a in s[::-1]:
res += (ord(a) - 64) * bit
bit *= 26
return res
# 递归 数5的个数
class Solution:
def trailingZeroes(self, n: int) -> int:
return n // 5 + self.trailingZeroes(n // 5) if n != 0 else 0
class BSTIterator:
def __init__(self, root: TreeNode):
self.stack = []
self.push_stack(root)
def next(self) -> int:
"""
@return the next smallest number
"""
tmp = self.stack.pop()
if tmp.right:
self.push_stack(tmp.right)
return tmp.val
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return bool(self.stack)
def push_stack(self, node):
while node:
self.stack.append(node)
node = node.left
# 动态规划
class Solution:
def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
row, col = len(dungeon), len(dungeon[0])
dp = [[0] * col for _ in range(row)]
dp[-1][-1] = max(1 - dungeon[-1][-1], 1)
for i in range(col - 2, -1, -1):
dp[-1][i] = max(1, dp[-1][i+1] - dungeon[-1][i])
for i in range(row - 2, -1, -1):
dp[i][-1] = max(1, dp[i+1][-1] - dungeon[i][-1])
for i in range(row - 2, -1, -1):
for j in range(col - 2, -1, -1):
dp[i][j] = max(min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j], 1)
return dp[0][0]
select FirstName, LastName, City, State
from Person left join Address
on Person.PersonId = Address.PersonId;
# limit
select (
select DISTINCT Salary
from Employee
order by Salary DESC
limit 1,1)
as SecondHighestSalary;
# max
select max(Salary) as SecondHighestSalary
from Employee
where Salary < (select max(Salary) from Employee);
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
# 定义变量
declare p int;
# 变量赋值
set p=n-1;
RETURN (
select ifnull(
(
# LIMIT a OFFSET b 方法
#select distinct salary from employee order by salary desc limit 1 OFFSET P
# LIMIT a,b 方法
select distinct salary from employee order by salary desc limit P,1
),null) as SecondHighestSalary
);
END
# 窗口
select score,
dense_rank() over(order by Score desc) as 'Rank'
from Scores;
# 清奇思路
select a.Score as Score,
(select count(distinct b.Score) from Scores b where b.Score >= a.Score) as Rank
from Scores a
order by a.Score DESC
class Solution:
def largestNumber(self, nums: List[int]) -> str:
from functools import cmp_to_key
def helper(x, y):
if x + y > y + x:
return -1
elif x + y < y + x:
return 1
else:
return 0
return "".join(sorted(map(str, nums), key=cmp_to_key(helper))).lstrip("0") or "0"
# pre变量统计上一次Num,cnt统计连续次数
SELECT DISTINCT a.Num ConsecutiveNums FROM (
SELECT t.Num ,
@cnt:=IF(@pre=t.Num, @cnt+1, 1) cnt,
@pre:=t.Num pre
FROM Logs t, (SELECT @pre:=null, @cnt:=0) b) a
WHERE a.cnt >= 3