好题
122 买卖股票任意次数操作
121 买卖股票(仅允许一次操作)
总结一下思路就是:如果第i天卖出股票,则最大利润为(该天的股价-前面天数中最小的股价),然后与已知的最大利润比较,如果大于则更新当前最大利润的值。厉害,学习了。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
lowest_price = prices[0]
best_profit = 0
for i in range(len(prices)):
today_price = prices[i]
lowest_price = min(lowest_price, today_price)
best_profit = max(best_profit, today_price - lowest_price)
return best_profit
122 买卖股票任意次数操作
其实这道题应该比121更简单的, 因为我们每次都可以任意操作, 只要能赚钱就行
def maxProfit(self, prices: List[int]) -> int:
total = 0
for i in range(1, len(prices)):
if prices[i] - prices[i -1] > 0:
total+= prices[i] - prices[i -1]
return total
当然, 本题的动态规划也很值得学习
class Solution:
def maxProfit(self, prices: List[int]) -> int:
have_stock = [0] * len(prices)
dont_have = [0] * len(prices)
have_stock[0] = -prices[0]
for i in range(1, len(prices)):
# 1.有股票, 不操作 -> 有股票
# 2.有股票, 卖了 -> 无股票
# 3.无股票, 不操作 -> 无股票
# 4.无股票, 买了 -> 有股票
# 1,4和2,3导致的结果相同, 应放在一起讨论
dont_have[i] = max(dont_have[i-1], have_stock[i-1] + prices[i])
have_stock[i] = max(have_stock[i -1], dont_have[i-1] - prices[i])
return max(max(dont_have), max(have_stock))
55 跳跃游戏
如果一个位置能够到达,那么这个位置左侧所有位置都能到达。 想到这一点,解法就呼之欲出了~
class Solution:
def canJump(self, nums: List[int]) -> bool:
furtherest = 0
for i in range(len(nums)):
if furtherest < i:
return False
else:
furtherest = max(furtherest, i + nums[i])
return furtherest >= len(nums) -1
45 跳跃游戏2
不仅是看能不能到, 更是要看到终点的最小次数
这是我的第一直觉, 用动态规划来记录到达位置i需要的最小次数
这个方法虽然能过但是
O
(
n
2
)
O(n^2)
O(n2)
class Solution:
def jump(self, nums: List[int]) -> int:
times = [len(nums) + 1] * len(nums)
times[0] = 0
for i in range(len(nums)):
for j in range(i + 1, min(len(nums), nums[i] + 1 + i)):
times[j] = min(times[j], times[i] + 1)
return times[len(nums) - 1]
想要O(n)的话本题还是得回到贪心
274 H-index
class Solution:
def hIndex(self, citations: List[int]) -> int:
citations.sort()
for i in range(len(citations)-1, -1,-1):
num = i + 1
index = len(citations) - 1 - i
if citations[index] >= num:
return num
return 0
这样先sort再做的方法应该都能想到
我还有一个想法是用哈希表来数各个引用次数出现的次数, 比如引用1次的:5篇, 引用2次的: 3篇.
但这样就比较棘手因为我们不知道最大的引用次数是多少, 但其实本文的h有个限制就是不可能超过论文的数量, 所以我们只用关心小于引用次数小于n的那些文章就可以了.
这样哈希都省了, 直接一个n维数组即可
class Solution:
def hIndex(self, citations: List[int]) -> int:
count = [0] * (len(citations) + 1)
for i in range(len(citations)):
if citations[i] > len(citations):
count[-1] += 1
else:
count[citations[i]]+=1
total = 0
for i in range(len(count)-1, -1, -1):
total += count[i]
if total >= i:
return i
return 0