1【双指针】接雨水-leecode42
维护两个指针left和right,以及两个变量leftMax和rightMax;
使用 height[left]和 height[right]的值更新leftMax和rightMax的值;
如果 height[left]<height[right]则必有 leftMax<rightMax,下标 left处能接的雨水量等于 leftMax−height[left]
class Solution(object):
def trap(self, height):
res = 0
leftmax, rightmax = 0, 0
left, right = 0, len(height)-1
while left < right:
leftmax = max(height[left], leftmax)
rightmax = max(height[right], rightmax)
if height[left]<height[right]:
res += leftmax - height[left]
left += 1
else:
res += rightmax-height[right]
right -= 1
return res
2【滑动窗口】-无重复字符的最长子串-leecode3
class Solution(object):
def lengthOfLongestSubstring(self, s):
showed = set()
n, res = len(s), 0
right = -1
for left in range(n):
if left != 0:
showed.remove(s[left-1])
# left指针,向右移动一格,移除前一个字符
while(right+1<n and s[right+1] not in showed):
showed.add(s[right+1])
right += 1
# right指针,向右移动
# 第 left 到 right个字符是一个极长的无重复字符子串
res = max(res, right-left+1)
return res
2最小面积矩阵-leecode939
1按列排序,2枚举对角线(x1,y1) (x2,y2) (x1,y2)(x2,y1)
class Solution(object):
def minAreaRect(self, points):
S = set(map(tuple, points))
ans = float('inf')
for idx, p2 in enumerate(points):
# 排列出对角点组合;注意enumerate和for i in range(idx)
for i in range(idx):
p1 = points[i]
if (
p1[0] != p2[0] and p1[1] != p2[1] and
(p1[0], p2[1]) in S and (p2[0], p1[1]) in S
):
ans = min(ans, abs(p2[0] - p1[0]) * abs(p2[1] - p1[1]))
return ans if ans < float('inf') else 0
2矩阵(原地)旋转
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(n // 2):
for j in range((n + 1) // 2):
(
matrix[i][j],
matrix[n - j - 1][i],
matrix[n - i - 1][n - j - 1],
matrix[j][n - i - 1]
) = (
matrix[n - j - 1][i],
matrix[n - i - 1][n - j - 1],
matrix[j][n - i - 1],
matrix[i][j]
)
#方法2
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
# 水平翻转
for i in range(n // 2):
for j in range(n):
matrix[i][j], matrix[n - i - 1][j] = matrix[n - i - 1][j], matrix[i][j]
# 主对角线翻转
for i in range(n):
for j in range(i):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]