LeetCode 319. Bulb Switcher
来源:互联网 发布:排序算法比较次数 编辑:程序博客网 时间:2024/05/23 11:47
描述
给出一个组灯,按照规则开灯关灯后,有多少盏灯还亮着
解决
纸上写出来后,发现其中关灯的数量构成了2,4,6,8,10……的等差数列。用等差数列求和,然后比较判断即可。
class Solution {public: int bulbSwitch(int n) { int t = 1; int sum = 0; do{ sum = 2 * t + t * t; ++t; }while (sum <= n); --t; --t; sum = 2 * t + t * t; if (n - sum == 0) return t; else return t + 1; }};
看到别人一个机智的方法
一个数的因子总是成对出现的,只有因子数为奇数的时候,灯最后才会开着,而只有当开方位整数是才会存在奇数个因子,所以只需要sqrt(n),这样就可以得到答案,因为1~sqrt(n),总共存在sqrt(n)个这样的数。
class Solution {public: int bulbSwitch(int n) { return sqrt(n); }};
0 0
- [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
- 【LeetCode】319. Bulb Switcher
- [leetcode] 319.Bulb Switcher
- 【leetcode】319. Bulb Switcher
- [leetcode] 319. Bulb Switcher
- [LeetCode]319. Bulb Switcher
- 作用域闭包
- 十二之续、快速排序算法的深入分析
- Mac使用笔记(一):文件显示完整路径
- 备忘链接
- 设置paint.setXfermode(mMode)无效
- LeetCode 319. Bulb Switcher
- 十二之再续:快速排序算法之所有版本的c/c++实现
- Python-随请求发送data/headers
- 洛谷 P1019 [NOIP2000 T3] 单词接龙
- opencv学习(二)之图像的加载、显示、保存
- ECMAScript6笔记:let和const命令
- LoRa点对点系统3 与PC接口
- Android Studio 导入.so文件
- 解决SpringMVC表单重复提交总结