leetCode -Counting Bits

并网逆变器学习笔记8---平衡桥(独立中线模块)控制 参考文献:《带独立中线模块的三相四线制逆变器中线电压脉动抑制方法》---赵文心。 阅读详情

leetCode 解题报告之Counting Bits

1. 题目描述

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].

就是尝试在O(n)的时间复杂度里,对某一个数进行判断:其二进制中1的数量,就是使用动态规划,参照前后关系,因为由于是0-n,所以前后关系是有的。

0 对应 —0个1
1对应 —1个1
2对应 —1个1
3对应 —2个1
4对应 —1个1
5对应 —2个1


2. 解题思路描述

f(i)表示第i个数二进制中1的个数。

假设对某个数 n,
如果 n == 0; f(n)= 0;
如果n>=1 ; f(n)与f(n-1),f(n-2),f(n-3),。。。之间的关系是什么呢。

f[i] = f[i >> 1] + (i & 1);
其实这里采用的是f(i)和f(i右移一位)的关系。例如 1111 ,右移之后就是111,那也就是计算了除了最后一位的1的个数,那么如果i%2 == 0,最后一位为0,结果就是f(右移一位)。如果是i%2==1,结果就是f(右移一位)+1,那就是f(i)=f(i>>1)+i%2.
num is even: ret[num] = ret[num/2]
num is odd: ret[num] = ret[(num -1) / 2] + 1
so it can be reduced as: ret[i] = ret[i/2] + i % 2


f[i] = f[i&(i-1)] + 1;
这里是另外一种思路,寻找一个一直是f(i) 少一个1的数。 存不存在呢。
事实上是存在的,是不是很厉害,这里都是这些打码的家伙会去研究这个东西了。。。那就是i&(i-1)
假如最后一位为1,显然i&(i-1)只和i 相差最后一位的1.
假如最后一位不为1,为0,i-1 为偶数, i&i-1 刚好是去除最后一个一的结果。(膜)


3. 代码

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> result(num+1, 0);
        for (int i = 1; i <= num; ++i)
            result[i] = result[i&(i-1)] + 1;
        return result;
    }
};
把 ST03 的历史数据留得更久:ABAP Workload 统计保留期设置、原理与落地避坑指南 SAP ST03性能数据保留期配置指南 ST03/ST03N是SAP系统性能分析的核心工具,但默认数据保留期通常较短(3个月左右),难以满足跨季度对比、年度规划等需求。本文详细解析了ST03数据保留期的配置方法及注意事项: 数据存储机制:性能数据存储在监控库中,通过定期重组作业清理过期数据 配置路径:7.0+系统在"Workload Collector Database→Reorganization→Control"中按Profile分别设置 关键限制:保留期最大值建议不超过99,否则可 阅读详情

相关推荐

还在用iReport 5.6.0?手把手教你用JasperSoft Studio 6.8.0设计报表(附JDK 11+兼容方案)

本文详细介绍了从iReport 5.6.0迁移到JasperSoft Studio 6.8.0的全过程,包括JDK 11+环境配置、项目迁移实战、高级特性应用及常见问题解决方案。帮助开发者高效完成报表生成工具的升级,提升开发体验和报表性能。

weixin_30687051的博客 407

leetcode:Counting Bits

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

martin_liang的专栏 2220

VPI与Matlab协同仿真:相干光通信接收端DSP算法全解析

本文详细解析了如何利用VPI与Matlab协同仿真,构建完整的相干光通信接收端DSP算法处理闭环。重点介绍了从VPI导出数据后,在Matlab中实现时钟恢复、偏振解复用和载波相位估计等核心算法的步骤与原理,并阐述了如何通过误码率计算完成仿真验证,为相干光通信系统算法研究与验证提供了高效实用的方法。

ll5678的博客 609

Leetcode之Counting Bits

题目: Given a non negative integer numbernum. For every numbersiin the range0 ≤ i ≤ numcalculate the number of 1's in their binary representation and return them as an array. Example 1: Input: ...

qq_35455503的博客 210

基于RK3588的高效音视频对讲系统设计与实现

本文详细介绍了基于RK3588芯片的高效音视频对讲系统设计与实现。文章深入剖析了RK3588在8K编解码、高性能音频DSP及丰富接口方面的优势,并提供了从开发环境搭建、分层软件架构设计,到视频采集编码、音频回声消除及低延迟网络传输的完整实战指南,旨在帮助开发者充分利用该芯片硬件能力,构建稳定、低延迟的实时通信系统。

dapp9builder的博客 254

避坑指南:PyTorch ConvLSTM参数配置的那些坑(hidden_dim/kernel_size/num_layers详解)

本文深度解析PyTorch ConvLSTM中hidden_dim、kernel_size和num_layers三大核心参数的配置技巧,提供实战指南和性能优化建议。通过实验数据揭示参数组合的内在规律,帮助开发者避免常见配置陷阱,提升时空序列建模效果。特别针对视频预测、气象预报等应用场景,给出黄金参数组合方案和调试技巧。

vv45678的博客 702

leetcode笔记:Counting Bits

题目大意是,给定一个非负整数num,对于每一个满足0 ≤ i ≤ num的数字i,计算这些数字的二进制表示中1的个数,并以数组vector的形式返回。

liyuefeilong的专栏 5047

基于大模型的JMeter日志智能分析服务化实践

在软件性能测试领域,日志分析是定位系统瓶颈、评估稳定性的关键环节。传统基于规则或正则表达式的分析方法,在面对格式多变、上下文关联复杂的海量日志时,往往效率低下且难以深入。大语言模型(LLM)凭借其强大的自然语言理解与推理能力,为这一挑战提供了新的解决方案。其技术价值在于能够自动化地从非结构化文本中提取语义信息、关联分散的上下文,并生成可操作的根因分析与优化建议,从而将工程师从繁琐的日志筛查中解放出来,显著提升问题诊断的深度与效率。这一技术可广泛应用于自动化测试报告生成、实时监控预警、脚本调试辅助等工程实践场

weixin_28839549的博客 338

【Java】【LeetCode】338. Counting Bits

题目: Given a non negative integer numbernum. For every numbersiin the range0 ≤ i ≤ numcalculate the number of 1's in their binary representation and return them as an array. Example 1: Input: 2...

zhelong19830726的博客 351

螺丝锁付系统软件设计 C# Winform

视觉螺丝锁付系统软件设计 C# Winform ,这是其中通信子模块设计

weixin_42522973的博客 340

uniapp [安卓苹果App端] - 实现获取手机日历读写权限+调用本机日历数据及操作功能+日历中插入事项事件提醒,检测权限手机日历权限是否开启并引导用户同意授权,uniApp app端开启日历授权

uni-app,权限,手机日历权限,安卓Android,苹果ios,uniapp安卓android获取本机日历读写权限使用,uni-app获取日历权限并实现插入事项事件功能 uniapp苹果IOS系统不支持怎么办,判断权限,权限被拒绝了怎么办,获取日历权限报错,读取日历数据农历阴历并操作插入移除,给用户手机日历中放入一条提示,UniApp调用日历进行读写,打包上架后如何获取,安卓ios权限检测,安卓和ios权限获取,uniapp的APP端日历读写权限与使用示例代码,如何开启日历权限,日历的新增事项和删除,判

🏆 前端领域优质创作者 1万+

[leetcode] 338. Counting Bits

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

TstsUgeg的博客 3385

实战|基于Kappa架构的用户行为实时分析平台搭建教程

数据源:用Kafka存储全量数据(实时+历史),作为“事实来源”;处理引擎:用Flink等流处理引擎,读取Kafka中的数据,执行清洗、转换、聚合等操作;存储层:将处理结果写入实时存储(如Elasticsearch)或批量存储(如Hive);消费层:用可视化工具(如Kibana)展示结果,或提供API供业务系统调用。Kappa架构的关键设计原则全量数据存于Kafka:Kafka的“无限 retention”特性(默认保留7天,可配置更长)让它成为全量数据的存储介质;用流处理引擎处理所有数据。

Java大师兄的博客 797

leetcode 338. Counting Bits

来源:leetcode 338. Counting Bits 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

0_o_c 759

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

LeetCode 338. Counting Bits

338. Counting BitsGiven 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:

mingjc的博客 253

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

[leetcode]338. Counting Bits

[leetcode]338. Counting Bits Analysis 周五ummmmmm—— [啊啊啊啊 paper结果要出来了,心塞] Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in ...

weixin_32135877的博客 164

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

[LeetCode 338] Counting Bits

LeetCode 338. Counting Bits 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 ar

Smaug的专栏 608

leetcode 338 Counting Bits 详细解答

leetcode 338 Counting Bits 详细解答 以例子说明: Index :      0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 bin nums : 0 1 1 2 1 2 2 3 1 2 2  3    2   3   3   4   1

qq_22210659的博客 235

LeetCode-338. Counting Bits [C++][Java]

Given an integern, returnan arrayansof lengthn + 1such that for eachi(0 <= i <= n),ans[i]is thenumber of1'sin the binary representation ofi.

贫道绝缘子的博客 965

LeetCode 338. Counting Bits 题解

本题是位运算和动态规划的结合应用。利用位运算的性质动态规划状态转移时间复杂度 O(n)通过本题可以深入理解位运算的应用和动态规划的优化。

cannonjinx的博客 1757

LeetCode 338.Counting Bits 解题报告

LeetCode 338.Counting Bits 解题报告

骆小坑的填坑之旅 579

LeetCode OJ-338.Counting Bits

LeetCode OJ-338.Counting Bits题目描述 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 a

oYinGui1 590

Leetcode338. Counting Bits

计算二级制数中 1 的数目。

magic_jiayu的博客 219

LeetCode-338. Counting Bits

LeetCode-338. Counting Bits 题目描述:https://leetcode.com/problems/counting-bits/ 解题思路 当然,如果逐位取模再判断是不是1来计算1的个数当然可以,但这样时间复杂度就是O(n*sizeof(integer)) 了,我们想要O(n) 就好。 所以,在于对给定的数num ,我们对区间0 ≤ i ≤ num中的每个数求1 的...

ke1950523491的博客 273

Counting Bits LeetCode 高效解法解析与位运算技巧

Counting Bits是LeetCode第338题,要求计算从0到给定整数n之间每个数字的二进制表示中1的个数。这个问题看似简单,但高效解法涉及位运算和动态规划的巧妙结合

2509_93883384的博客 310

LeetCode 338.Counting Bits 题解(C++)

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.

prayyojay的博客 332
上一篇: LeetCode - jump game II
下一篇: LeetCode- Add two number I
Coder_zyq
博客等级 码龄10年 3粉丝 23原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值