摘要:题目要求思路和代码这里除了暴力的计算每个数字中含有多少个,我们可以使用动态规划的方法来计算中有几个。还有一种等价的思路是第位的的个数或是加上位构成的数字的的个数。
题目要求
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.思路和代码
这里除了暴力的计算每个数字中含有多少个1,我们可以使用动态规划的方法来计算i中有几个1。假设我们已经知道前i-1个数字分别有多少个1,而且i中含有k个数字,那么其实很容易的想到,i中1的个数等于前k-1位构成的数字的1的个数,加上第k位1的个数,即1或是0。还有一种等价的思路是第0位的1的个数(0或是1)加上1~k位构成的数字的1的个数。
public int[] countBits(int num) { int[] ans = new int[num + 1]; for (int i = 1; i <= num; ++i) ans[i] = ans[i & (i - 1)] + 1; return ans; }
public int[] countBits(int num) { int[] res = new int[num+1]; int cur = 1; while(cur <= num){ res[cur] = 1; cur <<= 1; } cur = 1; for(int i = 1 ; i<=num ; i++){ if(res[i] > 0){ cur = i; }else{ res[i] = res[i-cur] + 1; } } return res; }
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/71009.html
Problem Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1s in their binary representation and return them as an array. Example For num = 5...
摘要:空间复杂度方法是否为最大的幂的约数思路最大的的幂为,判断是否是的约数即可。复杂度时间复杂度,一个整数统计二进制的复杂度,最坏的情况下是。 大厂算法面试之leetcode精讲9.位运算视频教程(高效学习):点击学习目录:1.开篇介绍2.时间空间复杂度3.动态规划4.贪心5.二分查找6.深度优先&广度优先7.双指针...
摘要:依次移位复杂度思路依次移动位数进行计算。代码利用性质复杂度,思路代码 LeetCode[191] Number of 1 Bits Write a function that takes an unsigned integer and returns the number of ’1 bits it has (also known as the Hamming weight). Fo...
Problem Number of 1 BitsWrite a function that takes an unsigned integer and returns the number of ’1 bits it has (also known as the Hamming weight). Example For example, the 32-bit integer 11 has bina...
摘要:移位法复杂度时间空间思路最简单的做法,原数不断右移取出最低位,赋给新数的最低位后新数再不断左移。代码分段相或法复杂度时间空间思路标准的源码。更好的优化方法是将其按照分成段存储,节省空间。 Reverse Bits Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (r...
阅读 831·2021-11-15 11:37
阅读 3583·2021-11-11 16:55
阅读 3256·2021-11-11 11:01
阅读 984·2019-08-30 15:43
阅读 2720·2019-08-30 14:12
阅读 660·2019-08-30 12:58
阅读 3354·2019-08-29 15:19
阅读 1989·2019-08-29 13:59