LeetCode学习篇一——Counting Bits
来源:互联网 发布:在淘宝上怎样买东西 编辑:程序博客网 时间:2024/06/04 01:18
题目: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.
通过率:58.4% 难度:medium
解法一:一开始看到这道题,想到的就是直接算出每一个数二进制表示中1的个数然后放进一个向量中,再输出,虽然复杂度比较高,但是容易理解,代码也容易实现,在LeetCode上也通过了。时间复杂度为O(nlogn),主要代码如下:
vector<int> countBits1(int num) { vector<int> v; for(int i = 0; i <= num; i++) { int countOfOne = 0; int ti = i; while(ti != 0) { if(ti % 2 == 1) { countOfOne += 1; } ti /= 2; } v.push_back(countOfOne); } return v;}
解法二:虽然第一种解法通过了测试,但是还是想寻求一种复杂度更低的算法,所以尝试写出多个数字的二进制,尝试寻求规律,见下表:
通过观察表格可以发现第2、3个数的二进制1的位数是第1、2个数的分别加1,第5到8个数的二进制1的位数是前4个数的二进制1的位数分别对应加1,依次类推,发现每对应一组和2的幂方相关,于是不需要分别算出每个数的二进制1的位数,可以根据前面得到的来推出后面的,时间复杂度是O(n),代码如下:
vector<int> countBits(int num) { vector<int> v; if(num == 0) { v.push_back(0); return v; } v.push_back(0); v.push_back(1); int tnum = 2, k = 1; while(tnum <= num) { int v_size = v.size(); for(int i = pow(2,k); i < pow(2,k+1); i++) { v.push_back(v[i-v_size]+1); tnum++; if(tnum > num) { break; } } k++; } return v;}
0 0
- LeetCode学习篇一——Counting Bits
- LeetCode题解——Counting Bits
- LeetCode之338—-Counting Bits
- Leetcode算法学习日志-338 Counting Bits
- leetcode——338——Counting Bits
- leetcode:bits:Counting Bits(338)
- [leetcode] 338. Counting Bits
- 【LeetCode-338】Counting Bits
- leetcode-338-Counting Bits
- leetcode:Counting Bits
- [C]LeetCode:Counting Bits
- LeetCode Counting Bits
- leetcode 338. Counting Bits
- leetcode Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode#338. Counting Bits
- Leetcode 338 Counting Bits
- [LeetCode] 338. Counting Bits
- 关于linux下的TCP 的socket server和client,我的理解
- Lightoj 1107
- 关于忧虑
- 217. Contains Duplicate java
- 搜素框的制作
- LeetCode学习篇一——Counting Bits
- [LeetCode] 131. Palindrome Partitioning
- (转)解决VS2010链接错误:LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
- Binder机制(非常好理解)
- Uva227 Puzzle 谜题 (java版本)
- eclipse maven+mybatis+web项目(一)
- Context——Context的使用
- PATB1028:人口普查
- 磁盘分区