当前位置:网站首页>[算法] 剑指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
边栏推荐
- FairyGUI条子家族(滚动条,滑动条,进度条)
- MySQL時間、時區、自動填充0的問題
- What are the advantages of using SQL in Excel VBA
- Unity3d camera, the keyboard controls the front and rear left and right up and down movement, and the mouse controls the rotation, zoom in and out
- Flink late data processing (3)
- [offer78]合并多个有序链表
- MySQL performance tuning - dirty page refresh
- How to improve the deletion speed of sequential class containers?
- [Offer18]删除链表的节点
- 單片機藍牙無線燒錄
猜你喜欢
(1) Introduction Guide to R language - the first step of data analysis
FairyGUI人物状态弹窗
Lock wait timeout exceeded try restarting transaction
2021.11.10汇编考试
Intermediate use tutorial of postman [environment variables, test scripts, assertions, interface documents, etc.]
[Chongqing Guangdong education] Shandong University College Physics reference materials
使用rtknavi进行RT-PPP测试
idea问题记录
Compilation principle: preprocessing of source program and design and implementation of lexical analysis program (including code)
Fabrication d'un sac à dos simple fairygui
随机推荐
InnoDB dirty page refresh mechanism checkpoint in MySQL
FairyGUI按钮动效的混用
Servlet
1041 Be Unique (20 point(s))(哈希:找第一个出现一次的数)
Office提示您的许可证不是正版弹框解决
基于rtklib源码进行片上移植的思路分享
ORA-02030: can only select from fixed tables/views
Design and implementation of general interface open platform - (39) simple and crude implementation of API services
(3) Introduction to bioinformatics of R language - function, data Frame, simple DNA reading and analysis
使用rtknavi进行RT-PPP测试
Prove the time complexity of heap sorting
Unity3d, Alibaba cloud server, platform configuration
Flink late data processing (3)
idea中好用的快捷键
【rtklib】在rtk下使用抗差自适应卡尔曼滤波初步实践
ESP8266连接onenet(旧版MQTT方式)
Unity3d makes the registration login interface and realizes the scene jump
音乐播放(Toggle && PlayerPrefs)
服务未正常关闭导致端口被占用
Fairygui loop list