NC95数组中的最长连续子序列
给定无序数组arr,返回其中最长的连续序列的长度(要求值连续,位置可以不连续,例如 3,4,5,6为连续的自然数)
思路:使用集合的思想,对于arr中的数num,如果num-1在集合中,持续找,直到找到最小的数,然后再根据最小的数开始找集合中连续的数,更新max_length的值
class Solution:
def MLS(self , arr: List[int]) -> int:
# write code here
s=set(arr)
max_len=0
for num in arr:
if num-1 in s:
# 注意在列表arr中查找复杂度为o(n),在集合s中查找复杂度为o(1)
continue
cur_num=num
cnt=1
while cur_num+1 in s:
cur_num+=1
cnt+=1
max_len=max(max_len,cur_num)
return max_len
BM93盛水最多的容器
给定一个数组height,长度为n,每个数代表坐标轴中的一个点的高度,height[i]是在第i点的高度,请问,从中选2个高度与x轴组成的容器最多能容纳多少水
1.你不能倾斜容器
2.当n小于2时,视为不能形成容器,请返回0
3.数据保证能容纳最多的水不会超过整形范围,即不会超过231-1数据范围:
0<=height.length<=1050<=height[i]<=104
思路:盛水最多的容器只取决于短边,所以每次只要移动短边
class Solution:
def maxArea(self , height: List[int]) -> int:
# write code here
left=0
right=len(height)-1
max_water=0
water=0
while left<right:
if height[left]<height[right]:
water=(right-left)*height[left]
left+=1
else:
water=(right-left)*height[right]
right-=1
max_water=max(max_water,water)
return max_water



