【leetcode】338. Counting Bits
来源:互联网 发布:高中数学算法初步教案 编辑:程序博客网 时间:2024/06/05 01:53
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.
Example:
For num = 5 you should return [0,1,1,2,1,2].
Follow up:
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
这道题的要求时间和空间,其实它是有规律的,后面的和前面的相关。
javascript版本
Your runtime beats 69.46% of javascriptsubmissions
/** * @param {number} num * @return {number[]} */var countBits = function(num) { var final_nums = [0]; var i=1; var a=1; for(var i=1;i<num+1;i++){ if(i%a==0){ a=i; } final_nums.push(final_nums[i-a]+1); } return final_nums;};
Your runtime beats 95.81% of javascriptsubmissions.
/** * @param {number} num * @return {number[]} */var countBits = function(num) { var res = [0,1]; if(num === 0) return [0]; if(num===1){ return res; } var cc = 1; for(var i=2;i<=num;i++){ if(i%cc === 0){ cc = cc*2; } res.push(res[i-cc]+1); } return res;};
You are here!
Your runtime beats 98.80% of javascriptsubmissions.
/** * @param {number} num * @return {number[]} */var countBits = function(num) { var res = [0]; if(num === 0) return res; var cc = 1; for(var i=1;i<=num;i++){ if(i%cc === 0){ cc = i; } res.push(res[i-cc]+1); } return res;};
- [leetcode] 338. Counting Bits
- leetcode 338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode#338. Counting Bits
- [LeetCode] 338. Counting Bits
- LeetCode 338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode-338. Counting Bits
- LeetCode *** 338. Counting Bits
- (leetcode) 338. Counting Bits
- #leetcode#338. Counting Bits
- LeetCode 338. Counting Bits
- leetcode 338. Counting Bits
- LeetCode-338. Counting Bits
- LeetCode-338. Counting Bits
- leetcode-338. Counting Bits
- Leetcode 338. Counting Bits
- LeetCode 338. Counting Bits
- 【Leetcode】Duplicate Emails
- PHP笔记③数据类型
- 【转载】redis安装步骤
- 学习SpringMVC(五)之使用Servlet原生API
- ActionBar的用法
- 【leetcode】338. Counting Bits
- VoLTE——EPC附着
- 蓝缘系统business版本正式上线
- 我的第一篇CSDN博客
- 重要网站收藏
- 洛谷1080 国王游戏
- VoLTE—IMS注册
- Linux下安装nginx
- 阅读<java数据结构和算法>这本书的总结:第一章