242. valid anagram
给定两个字符串,问是否是 anagram(同字母异序)
python 的做法很简单,一行就好了
def isAnagram(self, s, t):
return sorted(s) == sorted(t)
这个是时间复杂度是 O(nlogn)
想要提高 速度的话 可以用 hash table
用两个list 存每个字符出现次数,然后比较。
时间复杂度是O(n), 但是空间复杂度也是O(n)
387: first unique character in a string
给一个string, 然后问string中只出现一次的 字符的最小的下标
首先想到的是字典:
def firstUniqChar(self, s):
Dic = {}
for char in s:
if char in Dic:
Dic[char] += 1
else:
Dic[char] = 1
for i in xrange(len(s)):
if Dic[s[i]] == 1:
return i
return -1
然后discussion里面有个更快的方法:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
letters='abcdefghijklmnopqrstuvwxyz'
index=[s.index(l) for l in letters if s.count(l) == 1]
return min(index) if len(index) > 0 else -1
时间复杂度都是O(n) 但是这里他只用了一个for loop而我用了两个。 这个用到了python 的 count 函数,可以mark 一下用法。
746 min cost climbing stairs
这个就是经典的爬楼梯的问题。用第一层往上走,每一次层有不同的weight,一次可以上一层或者两层,然后问上到顶层的最小的sum of weight 是多少。
就是一个简单的dp,公式如下:
dp[i] = min( dp[i - 1] + cost[i] , dp[i - 2] + cost[i] )
121. best time to sell stock
给一个list 告诉你stock 在index i 的value,然后问这个stock 最赚钱的值是多少,如果是一个降序的话输出是0
这道题一开始我以为要用O(n^2)
就是 遍历一边list, 然后在当前的index 的时候找它前面的 min,然后计算。
但是后来发现可以用一个global 的max_earn 表示最大值,然后用一个min_price 记录之前的最小值。比较当前的price -min_price 和max_earn 的大小。最后return max_earn 就好了
def maxProfit(self, prices):
max_earn, min_prices = 0, float('inf')
for price in prices:
min_prices = min(price, min_prices)
max_earn = max(max_earn, price - min_prices)
return max_earn