浏览更多/最多的文章数
2021-02-15 本文已影响0人
不分享的知识毫无意义
题目
某位用户连续一周登录简书浏览文章,假设他一周浏览文章的天数为一个list,记录为[5,10,2,4,5,3,15]。求解以下两个问题:
(1)该用户在登录几天后可以浏览比当天数量更多的文章数
以第3天为例,他当天浏览了2篇文章,在第4天浏览了4篇文章,那么此时的值应该为1
答案应该是:[1, 5, 1, 1, 2, 1, 0]
(2)该用户在登录几天后可以浏览最多的文章数
以第3天为例,他当天浏览了2篇文章,在第7天浏览了4篇文章,那么此时的值应该为4
答案应该是:[6, 5, 4, 3, 2, 1, 0]
解法
暴力求解
暴力是求解一切算法最好用的方法,这道题暴力求解很容易,直接两层循环解决
#题目1
def nextGreaterElements(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
nums_length = len(nums)
res_list = [0 for _ in range(nums_length)]
res_index = [0 for _ in range(nums_length)]
for i in range(nums_length):
for j in range(i+1,nums_length):
if nums[i] < nums[j]:
res_list[i] = nums[j]
res_index[i] = j-i
break
return res_list,res_index
print(nextGreaterElements([5,10,2,4,5,3,15])[1])
#题目2
def nextGreaterElements(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
nums_length = len(nums)
res_list = [0 for _ in range(nums_length)]
res_index = [0 for _ in range(nums_length)]
for i in range(nums_length):
for j in range(i+1,nums_length):
if nums[i] < nums[j]:
res_list[i] = nums[j]
res_index[i] = j - i
return res_list,res_index
print(nextGreaterElements([5,10,2,4,5,3,15])[1])
栈求解
栈求解的好处是只用遍历一遍
关于题目1:因为是求解下一个更长时间,所以预先需要设置一个栈存储之后元素,然后通过while不断弹出,而弹出的位置应该从头开始
关于题目2:因为求解最长的时间,因此需要不断的append最大值
#题目1
def nextGreaterElements(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
nums_length = len(nums)
res_list = [0 for _ in range(nums_length)]
res_index = [0 for _ in range(nums_length)]
for i in range(nums_length):
print(i)
stack = list(range(i+1,nums_length))
print(stack)
while stack and nums[i]>nums[stack[0]]:
stack.pop(0)
res_list[i] = nums[stack[0]] if stack else 0
res_index[i] = stack[0]-i if stack else 0
return res_list,res_index
print(nextGreaterElements([5,10,2,4,5,3,15])[1])
#题目2
def nextGreaterElements(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
nums_length = len(nums)
res_list = [0 for _ in range(nums_length)]
res_index = [0 for _ in range(nums_length)]
for i in range(nums_length-2,-1,-1):
stack = list(range(i+1,nums_length))
print(i)
while (nums[i]>nums[stack[-1]]):
stack.append(i)
print(stack)
res_list[i] = nums[stack[-1]]
res_index[i] = stack[-1]-i
return res_list,res_index
print(nextGreaterElements([5,10,2,4,5,3,15])[1])