您的位置:首页 > 编程语言 > Python开发

leetcode50_Pow(x, n)

2016-11-30 21:29 411 查看

一.问题描述

Implement pow(x, n).

实现指数乘法。

二.代码编写

首先想到的其实就是把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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法 python