leetcode50_Pow(x, n)

本文介绍了一种使用二分思想实现的快速幂算法,通过将指数不断拆分为n/2的形式来减少运算次数,从而将时间复杂度从O(N)降低到O(logN)。文章通过一个具体的例子解释了算法的基本思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.问题描述

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.youkuaiyun.com/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)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值