[Leetcode] 319. Bulb Switcher 解题报告
来源:互联网 发布:photoshop cs软件下载 编辑:程序博客网 时间:2024/06/08 05:43
题目:
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 ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.
Example:
Given n = 3.
At first, the three bulbs are [off, off, off].After first round, the three bulbs are [on, on, on].After second round, the three bulbs are [on, off, on].After third round, the three bulbs are [on, off, off].
So you should return 1, because there is only one bulb is on.
思路:
1、朴素解法:朴素解法比较简单,没有算法技巧,可惜过不了所有数据。
2、质因数法:仔细分析这道题目就会发现,在n遍循环中,改变第i个灯泡状态的只有i的因数(而不是质因数)。例如8,那么在1,2,4,8遍的时候状态就会改变;而对于9而言,在第1,3,9遍的时候会改变状态。发现规律了吗?就是对于非平方数而言,状态会被改变奇数次;对于平方数而言,状态只会被改变偶数次,因而最终灯一定是灭的。所以这道题目实际上只需要返回小于等于n的平方数的个数就可以了,数学的魅力很神奇有木有?
好消息是:据说FLAG现在已经不考这种类似于智力题的东西了,所以大家做着玩一玩就可以了^_^。
代码:
1、朴素解法:
class Solution {public: int bulbSwitch(int n) { vector<bool> status(n, false); for(int i = 1; i <= n; ++i) { for (int j = i - 1; j < n; j += i) { status[j] = !status[j]; } } int ret = 0; for (int i = 0; i < n; ++i) { if (status[i]) { ++ret; } } return ret; }};
2、质因数法:
class Solution {public: int bulbSwitch(int n) { return sqrt(n); }};
阅读全文
0 0
- [leetcode] 319. Bulb Switcher 解题报告
- LeetCode 319. Bulb Switcher 解题报告
- [Leetcode] 319. Bulb Switcher 解题报告
- 319. Bulb Switcher解题报告
- LeetCode---Bulb Switcher解题分析
- [leetcode] 319. Bulb Switcher
- leetcode 319. Bulb Switcher
- 319. Bulb Switcher LeetCode
- LeetCode 319. Bulb Switcher
- LeetCode *** 319. Bulb Switcher
- [leetcode]319. Bulb Switcher
- leetcode-319. Bulb Switcher
- leetcode 319. Bulb Switcher
- leetcode 319. Bulb Switcher
- 【leetcode】319. Bulb Switcher
- [Leetcode] 319. Bulb Switcher
- LeetCode-319.Bulb Switcher
- Leetcode 319. Bulb Switcher
- 安装orcle12C碰到“无法访问临时位置”的问题处理
- java内存区域划分
- 乒乓球
- Struts2动态参数封装
- 1090. Highest Price in Supply Chain (25)<BFS,DFS>
- [Leetcode] 319. Bulb Switcher 解题报告
- Android_传感器
- WatchOS系统开发大全(6)-WKInterfaceLabel
- 【剑指offer】面试题32(3):之字形打印二叉树
- 【python】在图片加上数字
- 数组元素标记法
- Python线程同步
- 计算机设计思想 —— 分层模型
- 新闻网页类开发html和iOS原生交互