1. 程式人生 > >Leetcode amazon 面試題(二)

Leetcode amazon 面試題(二)

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