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)




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