记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
二分
因为边界为负无穷
只要往高坡移动 必定能找到峰值
def findPeakElement(nums):
"""
:type nums: List[int]
:rtype: int
"""
l,r = 0,len(nums)-1
while l<r:
mid = l+((r-l)>>1)
if nums[mid]<nums[mid+1]:
l = mid+1
else:
r = mid
return l
按每一行来二分 对于某一行i来说 取其中最大值mat[i][j]
判断该最大值与上下相邻值的关系
如果都大于邻值 说明该位置为峰顶
如果存在大的邻值 说明该方向存在峰顶
def findPeakGrid(mat):
"""
:type mat: List[List[int]]
:rtype: List[int]
"""
l,r = 0,len(mat)-2
while l<=r:
mid = (l+r)>>1
mx = max(mat[mid])
j = mat[mid].index(mx)
if mx>mat[mid+1][j]:
r = mid-1
else:
l = mid+1
i = l
return [i,mat[i].index(max(mat[i]))]
依次判断
def isAcronym(words, s):
"""
:type words: List[str]
:type s: str
:rtype: bool
"""
n = len(words)
if n!=len(s):
return False
for i in range(n):
if words[i][0]!=s[i]:
return False
return True
以i为山顶
计算0~i能够得到的最大和left[i]
计算i~n能够得到的最大和right[i]
left[i]+right[i+1]就是最大和
单调栈来统计
def maximumSumOfHeights(maxHeights):
"""
:type maxHeights: List[int]
:rtype: int
"""
n=len(maxHeights)
right = [0]*(n+1)
st = [n]
s = 0
for i in range(n-1,-1,-1):
v = maxHeights[i]
while len(st)>1 and v<=maxHeights[st[-1]]:
j = st.pop()
s -= maxHeights[j]*(st[-1]-j)
s+=v*(st[-1]-i)
right[i]=s
st.append(i)
ans = s
st=[-1]
l = 0
for i,v in enumerate(maxHeights):
while len(st)>1 and v<=maxHeights[st[-1]]:
j = st.pop()
l -= maxHeights[j]*(j-st[-1])
l+=v*(i-st[-1])
ans = max(ans,l+right[i+1])
st.append(i)
return ans
左侧到山顶是递增 山顶到右侧是递减
只考虑一边 即求递增子序列
另一边倒序后 同样求递增子序列
def minimumMountainRemovals(nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
def getLIS(nums):
dp=[1]*n
for i in range(n):
for j in range(i):
if nums[j]<nums[i]:
dp[i] = max(dp[i],dp[j]+1)
return dp
left = getLIS(nums)
right = getLIS(nums[::-1])[::-1]
ans = 0
for i,j in zip(left,right):
if i>1 and j>1:
ans = max(ans,i+j-1)
return n-ans
大顶堆 每次取最大一堆石子进行操作
def minStoneSum(piles, k):
"""
:type piles: List[int]
:type k: int
:rtype: int
"""
import heapq
s = sum(piles)
l = [-x for x in piles]
heapq.heapify(l)
while k>0:
v = -heapq.heappop(l)
s -= v//2
v -= v//2
heapq.heappush(l,-v)
k-=1
return s