当前位置:网站首页>[算法] 剑指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

边栏推荐
- How to improve the deletion speed of sequential class containers?
- Servlet
- FairyGUI增益BUFF数值改变的显示
- [899] ordered queue
- PR 2021 quick start tutorial, first understanding the Premiere Pro working interface
- FairyGUI复选框与进度条的组合使用
- Intermediate use tutorial of postman [environment variables, test scripts, assertions, interface documents, etc.]
- HCIP Day 12
- (5) Introduction to R language bioinformatics -- ORF and sequence analysis
- Solution to the problem of automatic login in Yanshan University Campus Network
猜你喜欢

NRF24L01 troubleshooting

【干货】提升RTK模糊度固定率的建议之周跳探测

Single chip Bluetooth wireless burning

FairyGUI循环列表

Affichage du changement de valeur du Buff de gain de l'interface graphique de défaillance

Esp8266 connect onenet (old mqtt mode)

What are the advantages of using SQL in Excel VBA

NRF24L01故障排查

Unity场景跳转及退出

服务未正常关闭导致端口被占用
随机推荐
MySQL replacement field part content
SVN更新后不出现红色感叹号
C programming exercise
服务未正常关闭导致端口被占用
[Offer29] 排序的循环链表
Design and implementation of general interface open platform - (39) simple and crude implementation of API services
Problèmes avec MySQL time, fuseau horaire, remplissage automatique 0
VLSM variable length subnet mask partition tips
GNSS定位精度指标计算
Office prompts that your license is not genuine pop-up box solution
地球围绕太阳转
Special palindromes of daily practice of Blue Bridge Cup
Lean product development - Lean Software Development & lean product development
Latex learning
Detailed explanation of truncate usage
NRF24L01 troubleshooting
By v$rman_ backup_ job_ Oracle "bug" caused by details
(课设第一套)1-4 消息传递接口 (100 分)(模拟:线程)
RTKLIB: demo5 b34f.1 vs b33
Flink late data processing (3)