leetcode50_Pow(x, n)

一.問題描述

Implement pow(xn).

實現指數乘法。


二.代碼編寫

首先想到的其實就是把n不斷拆分成n/2,但是想歪了,可能沉浸在大數乘法那個題裏,然後發現其實小數乘大數比兩個相等的數運算複雜度低一點,所以就否定了這個想法。但看了tags是二分的思想,後來一想其實重點不在於每次運算的複雜度,而在於二分能將運算的次數由O(N)降低到O(logN)。

所以其實這題很簡單啦。重點是不要想偏了!

'''
@ author: wttttt at 2016.11.29
@ problem description see: https://leetcode.com/problems/anagrams/
@ solution explanation see: http://blog.csdn.net/u014265088/article/
@ github:https://github.com/wttttt-wang/leetcode
@ hash table, use python dictionary
@ its better to use sorted(i) as the key
'''
class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        d,ans= {},[]
        for i in strs:
            sortstr = ''.join(sorted(i))  # use sorted(i) as the key in the dictionary
            if sortstr in d:
                d[sortstr] += [i]
            else:
                d[sortstr] = [i]
        #print(d)
        for i in d:
            tmp = d[i];tmp.sort()
            ans += [tmp]
        return ans

so = Solution()
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
print so.groupAnagrams(strs)




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章