当前位置:网站首页>[算法] 剑指offer2 golang 面试题3:前n个数字二进制形式中1的个数
[算法] 剑指offer2 golang 面试题3:前n个数字二进制形式中1的个数
2022-07-06 09:18:00 【邓嘉文Jarvan】
[算法] 剑指offer2 golang 面试题3:前n个数字二进制形式中1的个数
题目1:
给定一个非负整数 n ,请计算 0 到 n 之间的每个数字的二进制表示中 1 的个数,并输出一个数组。
示例 1:
输入: n = 2
输出: [0,1,1]
解释:
0 --> 0
1 --> 1
2 --> 10
示例 2:
输入: n = 5
输出: [0,1,1,2,1,2]
解释:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
说明 :
0 <= n <= 105
func countBits(n int) []int {
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/w3tCBm
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路1:
思路1: 暴力计算每一个数字的每一位1的个数,时间复杂度 O(n*17),10^5 < ^17
代码
func countBits(n int) []int {
//思路1: 暴力计算每一个数字的每一位1的个数,时间复杂度 O(n*17),10^5 < ^17
//参数处理
if n == 0 {
return []int{
0}
}
res := make([]int,n+1)
for i:=0;i <=n;i++{
count := 0
for j:=0;j<17;j ++{
if i & (1 << j) != 0 {
count ++
}
}
res[i] = count
}
return res
}
测试

思路2:
// 要点: i&(i-1)就是比i中1少一个的数字
// 我们可以通过之前求到的i中1的个数来求,时间复杂度是 O(n)
代码2
func countBits(n int) []int {
// 要点: i&(i-1)就是比i中1少一个的数字
// 我们可以通过之前求到的i中1的个数来求,时间复杂度是 O(n)
if n == 0 {
return []int{
0}
}
res := make([]int,n+1)
res[0] = 0
for i:=1;i <=n;i++{
res[i] = res[i&(i-1)] + 1
}
return res
}
测试2

边栏推荐
- Servlet
- [Offer18]删除链表的节点
- [offer9]用两个栈实现队列
- Mysql database index
- Database table splitting strategy
- How to add music playback function to Arduino project
- Comparative analysis of the execution efficiency of MySQL 5.7 statistical table records
- Office prompts that your license is not genuine pop-up box solution
- [leetcode622] design circular queue
- How to improve the deletion speed of sequential class containers?
猜你喜欢

FairyGUI增益BUFF数值改变的显示

單片機藍牙無線燒錄

Matlab读取GNSS 观测值o文件代码示例

使用rtknavi进行RT-PPP测试

(core focus of software engineering review) Chapter V detailed design exercises

In 2020, the average salary of IT industry exceeded 170000, ranking first

平衡二叉树详解 通俗易懂

Gravure sans fil Bluetooth sur micro - ordinateur à puce unique

Idea problem record

ORA-02030: can only select from fixed tables/views
随机推荐
dosbox第一次使用
Fairygui gain buff value change display
Gravure sans fil Bluetooth sur micro - ordinateur à puce unique
FairyGUI简单背包的制作
InnoDB dirty page refresh mechanism checkpoint in MySQL
Special palindromes of daily practice of Blue Bridge Cup
idea问题记录
Fairygui loop list
MySQL performance tuning - dirty page refresh
Particle system for introduction to unity3d Foundation (attribute introduction + case production of flame particle system)
[Clickhouse kernel principle graphic explanation] about the collaborative work of partitioning, indexing, marking and compressed data
Liste des boucles de l'interface graphique de défaillance
基本Dos命令
服务未正常关闭导致端口被占用
[899] ordered queue
Easy to use shortcut keys in idea
Force buckle 1189 Maximum number of "balloons"
Programming homework: educational administration management system (C language)
Comparative analysis of the execution efficiency of MySQL 5.7 statistical table records
By v$rman_ backup_ job_ Oracle "bug" caused by details