Leetcode-319 Bulb Switcher

Problem restatement

There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it’s off or turning off if it’s on). For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

Resolution one

先给出最笨、最简单的办法(后来会发现存在很多问题):

class Solution(object):
    def bulbSwitch(self, n):
        """
        :type n: int
        :rtype: int
        """
        bulb = [0]*n
        for i in range(1,n+1):
            for j in range(1,n/i+1):
                k=i*j-1
                bulb[k]=1-bulb[k]
        return sum(bulb)

提示:超过给定的时间限制。所以需要改进,思想是该减少循环的的次数。

Problem analysis

把灯泡按顺序标号为 1n ,如果灯泡 k 被操作 pk 次,如果 pk 为偶数那么其最后的状态为off,否则就是on。进而, pk 等于 k 的所有因子个数,并且因子具有对称性,所有只要观察 k 是否为平方数即可。

Resolution two and three

按照上述的思想,及得到如下的方案。

class Solution(object):
    def bulbSwitch(self, n):
        """
        :type n: int
        :rtype: int
        """
        bulb = [0]*n
        for i in range(1,n+1):
            temp = int(i**0.5)
            if temp*temp==i:
                bulb[i-1]=1
        return sum(bulb)

提示为:限定的内存溢出。接下来就要减小内存的开销。其实发现,bulb初始化和最后求和是没有必要的,可以直接计数。得到方案三:

class Solution(object):
    def bulbSwitch(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        for i in range(1,n+1):
            temp = int(i**0.5)
            if temp*temp==i:
                count += 1
        return count

仍然提示为:限定的内存溢出。从这得知,内存的开销在开方,但是又无法避免。

Final resolution

做到这一步,不管怎么修改都是内存溢出。开始分析给定自然数之前的完全平方数。
我们发现:
n = 1 时,之前只有1个完全平方数;
n = 4 时,之前只有2个完全平方数;
n = 6 时,之前只有2个完全平方数;
n = 9 时,之前只有3个完全平方数;

所以,对于给定的 n ,之前有 floor(n) 个完全平方数,也就是最后有 floor(n) 个灯泡是on状态。最终得到的方案为:

class Solution(object):
    def bulbSwitch(self, n):
        """
        :type n: int
        :rtype: int
        """
        t = int(n**0.5)
        return t

终于通过了。

Leetcode 官网
https://leetcode.com/problemset/algorithms/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值