记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
8/7 344. 反转字符串
双指针
def reverseString(s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
l,r=0,len(s)-1
while l<r:
s[l],s[r]=s[r],s[l]
l+=1
r-=1
8/8 1749. 任意子数组和的绝对值的最大值
记录最小值 最大值
def maxAbsoluteSum(nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
ans = 0
minv,maxv = 0,0
r = 0
while r<n:
minv+=nums[r]
maxv+=nums[r]
if maxv>0:
ans = max(ans,maxv)
else:
maxv = 0
if minv<0:
ans = max(ans,-minv)
else:
minv = 0
r+=1
return ans
8/9 1281. 整数的各位积和之差
按要求计算
def subtractProductAndSum(n):
"""
:type n: int
:rtype: int
"""
a,b = 1,0
while n>0:
v = n%10
a *= v
b += v
n//=10
return a-b
8/10 1289. 下降路径最小和 II
从上到下遍历每一行
在每一行中记录最小值和次小值 及其位置
下一行使用到的必定只有这两个值
def minFallingPathSum(grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
first,second = (float("inf"),-1),(float("inf"),-1)
for i in range(n):
one,two = float("inf"),float("inf")
f,s = -1,-1
for j in range(n):
cur = grid[i][j]
if i!=0:
if j==first[1]:
cur+=second[0]
else:
cur+=first[0]
if cur<one:
two = one
one = cur
f = j
elif cur<two:
two = cur
s=j
first = (one,f)
second = (two,s)
return first[0]
8/11 1572. 矩阵对角线元素的和
计算每行需要累加的数位置
def diagonalSum(mat):
"""
:type mat: List[List[int]]
:rtype: int
"""
ans = 0
n= len(mat)
for i in range(n):
ans += mat[i][i]
j = n-1-i
if i!=j:
ans+=mat[i][j]
return ans
8/12 23. 合并 K 个升序链表
将每个链表当前值放入小顶堆中
依次取堆中最小值 并将下一个节点放入文章来源:https://www.toymoban.com/news/detail-650003.html
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeKLists(lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
import heapq
h = ListNode(0)
cur = h
l = []
n = len(lists)
for i in range(n):
if lists[i]:
heapq.heappush(l, (lists[i].val,i))
lists[i]=lists[i].next
while l:
v,idx = heapq.heappop(l)
cur.next = ListNode(v)
cur = cur.next
if lists[idx]:
heapq.heappush(l,(lists[idx].val,idx))
lists[idx]=lists[idx].next
return h.next
8/13 88. 合并两个有序数组
从大到小考虑文章来源地址https://www.toymoban.com/news/detail-650003.html
def merge(nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
cur = m+n-1
l,r=m-1,n-1
while r>=0:
while l>=0 and nums1[l]>nums2[r]:
nums1[cur],nums1[l]=nums1[l],nums1[cur]
cur-=1
l-=1
nums1[cur],nums2[r]=nums2[r],nums1[cur]
cur-=1
r-=1
到了这里,关于LeetCode 每日一题 2023/8/7-2023/8/13的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!