LeetCode题解:Counting Bits
2017-02-04 18:06
381 查看
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
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.
思路:
观察可知:
return them as an array.
Example:
For
num = 5you 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.
思路:
观察可知:
| 0 0 0 0 -- 0 | 0 0 0 1 -- 1 | 0 0 1 0 -- 1 | 0 0 1 1 -- 2 | 0 1 0 0 -- 1 | 0 1 0 1 -- 2 | 0 1 1 0 -- 2 | 0 1 1 1 -- 3 | 1 0 0 0 -- 1 | 1 0 0 1 -- 2 | 1 0 1 0 -- 2 | 1 0 1 1 -- 3 | 1 1 0 0 -- 2 | 1 1 0 1 -- 3 | 1 1 1 0 -- 3 | 1 1 1 1 -- 4题解:
#include <vector> std::vector<int> countBits(int num) { std::vector<int> result(num + 1); // extra 0 at beginning result[0] = 0; int z = 1; while((z << 1) <= num) { for(int i = 0; i < z; ++i) { result[i + z] = result[i] + 1; } z <<= 1; } for(int i = 0; z <= num; ++i, ++z) { result[z] = result[i] + 1; } return result; }
相关文章推荐
- LeetCode题解——Counting Bits
- [LeetCode]题解(python):096-Unique Binary Search Trees
- leetcode题解-125. Valid Palindrome && 680. Valid Palindrome II
- leetCode -Counting Bits
- Leetcode 338 Counting Bits
- 【LeetCode题解】309. Best Time to Buy and Sell Stock with Cooldown
- LeetCode题解:Odd Even Linked List
- 再从萌新开始-Leetcode每日题解-153. Find Minimum in Rotated Sorted Array
- LeetCode题解——Add Two Numbers
- LeetCode题解:Remove Linked List Elements
- 再从萌新开始-Leetcode每日题解-667. Beautiful Arrangement II
- leetcode题解-463. Island Perimeter
- LeetCode 338 -Counting Bits ( JAVA )
- LeetCode题解——Swap Nodes in Pairs
- LeetCode 96. Unique Binary Search Trees 题解
- leetcode题解日练--2016.7.16
- Leetcode题解-55. Jump Game
- 【Leetcode】Counting Bits
- LeetCode题解:Two Sum
- Leetcode题解 268. Missing Number