zoukankan      html  css  js  c++  java
  • leetcode python 350. 两个数组的交集 121. 买卖股票的最佳时机


    350. 两个数组的交集

    给定两个数组,编写一个函数来计算它们的交集。

    输入:nums1 = [1,2,2,1], nums2 = [2,2]
    输出:[2,2]

    class Solution:
        def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
            tem=[]
            for i in nums1:
                if i in nums2:
                    tem.append(i)
                    nums2.remove(i)
            return tem
    

    执行用时:48 ms, 在所有 Python3 提交中击败了26.97%的用户
    内存消耗:15.1 MB, 在所有 Python3 提交中击败了47.33%的用户

    121. 买卖股票的最佳时机

    给定一个数组prices,它的第i个元素prices[i]表示一支给定股票第i天的价格。

    你只能选择某一天买入这只股票,并选择在未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

    返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回0

    输入:[7,1,5,3,6,4]
    输出:5
    解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
    注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。

    class Solution:
        def maxProfit(self, prices: List[int]) -> int:
            max = 0
            tem = 0
            for i in range(len(prices)):
                for j in range(i,len(prices)):
                    tem = prices[j]-prices[i]
                    if tem >= max:
                        max = tem
            return max
    

    执行结果:超出时间限制

    class Solution:
        def maxProfit(self, prices: List[int]) -> int:
            dp0 = 0
            dp1 = - prices[0]
            dp2 = float('-inf')
            for i in range(1, len(prices)):
                dp1 = max(dp1, dp0 - prices[i])
                dp2 = max(dp2, dp1 + prices[i])
            return max(dp0, dp2)
    
    

    执行用时:276 ms, 在所有 Python3 提交中击败了29.31%的用户内存消耗:23 MB, 在所有 Python3 提交中击败了36.35%的用户

    去他丫的复杂度,又不是不能用hhhimage

  • 相关阅读:
    散列表(Hash Table)
    MVC中TextBox事件
    AJAX控制DropDownList两级联动
    唯一标示
    检查对象属性是否有空值
    foreach枚举div控制单个显示
    JS获取DropDownList其中一项的文本值
    随便
    MVC常用
    不可用输入框
  • 原文地址:https://www.cnblogs.com/hereisdavid/p/15270226.html
Copyright © 2011-2022 走看看