Leetcode Data Structure [350 | 121]

[Data Structure Study Plan] - Day 2

350. Intersection of Two Arrays II

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

import collections
class Solution:
    def intersect(self, nums1, nums2):
        a, b = map(collections.Counter, (nums1, nums2))
        return list((a & b).elements())

Remark: Library collections

Import library collections and use collections.Counter to get the result.

Feedback:

Runtime: 63 ms, faster than 56.61% of Python3 online submissions for Intersection of Two Arrays II.

Memory Usage: 14.1 MB, less than 77.61% of Python3 online submissions for Intersection of Two Arrays II.

Solution2. 

class Solution:
    def intersect(self, nums1, nums2):
        t = []
        for i in set(nums1) & set(nums2):
            t += [i]*min(nums1.count(i), nums2.count(i))
        return t

Remark:

        Uniqueness of sets: screen out candidates

        List.count(): number of every candidate

Feedback:

Runtime: 68 ms, faster than 48.52% of Python3 online submissions for Intersection of Two Arrays II.

Memory Usage: 14.1 MB, less than 77.61% of Python3 online submissions for Intersection of Two Arrays II.


121. Best Time to Buy and Sell Stock

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

class Solution:
    def maxProfit(self, prices):
        buy, max_profit = max(prices), 0
        for price in prices:
            buy = min(buy, price)
            profit = price - buy
            max_profit = max(max_profit, profit)
        return max_profit

Remark: Dynamic Iterating

Step1. for loop: to iterate every current price i.e. Everytime we have a partition of list splitted by the current element (price).

Step2. buy: minimum of the first part of list

Step3. profit = current element - buy

Step4. update the maximum profit

Feedback:

Runtime: 1124 ms, faster than 71.41% of Python3 online submissions for Best Time to Buy and Sell Stock.

Memory Usage: 25 MB, less than 66.96% of Python3 online submissions for Best Time to Buy and Sell Stock.

To be continued... : )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值