[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... : )