longest continuous subsequence of 0s

CSDN每日一练 |『贝博士发奖金』『Longest Continuous Increasing Subsequence』『最小差值』2023-09-01 🟢 编程路上,每日一练,不断精进!🔊『贝博士发奖金』『Longest Continuous Increasing Subsequence』『最小差值』。 阅读详情

Michal Forišek
Michal Forišek, teacher, scientist, competitive programmer
15.4k Views  • Upvoted by  Alon Amit,  CS degree and many years of coding.
Michal is a Most Viewed Writer in  Big-O Notation.

This problem has a much faster solution than the one (probably) required in the question. For a given n it is solvable in only O(log log n) basic bitwise instructions. Below I'm using b-bit unsigned integers and I show how to find the longest contiguous sequence of 0 bits in O(log b) time. Basically, we will use a clever binary search.

First step: zeros at the end as a special case. On many modern processors this can be done in constant time by using a specialized instruction (http://en.wikipedia.org/wiki/Cou...), but even in its absence it is easy to find their count in O(log b) time.

After we count the trailing zeros, we change them to ones to get rid of them. Then we get to  general case. Let z be the input number, after we changed the trailing 0s to 1s.

Imagine the zeros as empty space, and ones as bushes:
example:
       z = .....11......1...1

Note that we have at least one bush at the right end.
The bushes will grow towards the left, one step at a time. We can grow the bushes by one step by computing z | z<<1:
example:     
       z = .....11......1...1
    z<<1 = ....11......1...1.
  z|z<<1 = ....111.....11..11

(The operator | is bitwise or, the operator << is left shift.)

We will use s(i) to denote the configuration obtained from z after i steps.
So far, we know that s(0)=z and that s(1) can be computed as z | z<<1.

At this point it should be obvious that the length of the longest sequence of consecutive 0s is equal to the number of steps it takes until the bushes cover everything. That is, we are looking for the smallest x such that s(x) has all 1s.
If s(0) or s(1) have this property, we are done.

Let's do one more step, now with z=s(1):
example:
       z = ....111.....11..11
    z<<1 = ...111.....11..11.
  z|z<<1 = ...1111....111.111


The bottom line shows the state s(2). Each gap is now 2 shorter than it was in the beginning.

Of course, now we could continue growing the bushes one step at a time and checking whether we are done after each step. This would give us a nice simple solution in O(b) steps. But we are smarter than that! We will speed up the growth of our bushes exponentially.

Note that currently each cluster of bushes has more than two of them. Thus, we can now simulate two more steps at once by computing z | z<<2:
example:
       z = ...1111....111.111
    z<<2 = .1111....111.111..
  z|z<<2 = .111111..111111111


The bottom line of the example above shows the configuration s(4). 
We can now use s(4) to compute s(8) as s(4) | s(4)<<4. Next, we use s(8) to compute s(16), and so on, until we get a state with all 1s. (Note that this must happen in at most log b iterations.)

What shall we do next?
Let's see it on an example. Suppose that s(8) still has some gaps but s(16) has none. This tells us that in the original configuration the length of the longest segment of 0s is between 9 and 16, inclusive. To find the exact length, we will now use binary search on the interval (8,16].

How to do the binary search?
Continuing our example, we now want to check whether there are some 0s present in s(12). How can we compute s(12)? This is easy: s(12) = s(8) | s(8)<<4.
From s(8) we can compute in constant time each of the configurations we might need during the binary search by using different shift amounts.

Thus, in our solution we use O(log b) instructions to find an interval of the form ( 2^i, 2^(i+1) ] that contains the answer, and then we use another O(log b) instructions to find the exact answer using binary search.

Sample implementation:  http://ideone.com/unp7hD
(update: simplified code according to a suggestion by  Obinna Okechukwu)
Benchmarks on my machine: ~6x faster than the O(b) version when iterating over all 32-bit unsigneds, ~9x faster than O(b) version for random 64-bit unsigneds.



In practice we can do even better, we just need to spend some memory. If we precompute the answers and also the number of leading/trailing zeros for 16-bit unsigneds, we can easily combine them into answers for longer numbers. For 32-bit integers this approach is more than 2x faster than the O(log b) version in my benchmarks
螺杆挤压机温控为何必须用S1500 PLC+RKC模块? 工业温控系统中,高精度温度调节依赖于传感采集、闭环算法与执行响应的协同优化。其核心原理在于消除采样噪声、缩短控制周期、抑制现场干扰,并实现多区动态耦合。技术价值体现在±0.5℃稳态精度、<20ms轮询响应及抗电磁干扰鲁棒性,广泛应用于PVC/PE造粒、电缆护套等连续挤出场景。当面对螺杆机强干扰、多温区、快变负载等典型工况时,通用PLC难以满足实时性与稳定性要求,而S1500 PLC与RKC温控模块构成的Modbus RTU专用闭环方案,凭借高速轮询、硬件级滤波和工程化寄存器映射,成为行业事实标准。 阅读详情

相关推荐

Ubuntu 20.04 + CARLA 0.9.13 长时运行崩溃?手把手教你定位和缓解Segmentation fault

本文详细解析了Ubuntu 20.04环境下CARLA 0.9.13仿真平台长时运行崩溃问题,提供了从内存监控到核心转储分析的系统级诊断方法,并分享内存泄漏缓解、稳定性优化配置等实用解决方案,帮助开发者构建更稳定的自动驾驶仿真环境。

weixin_28362173的博客 259

Sort a linked list of 0s, 1s and 2s

转自:http://www.geeksforgeeks.org/sort-a-linked-list-of-0s-1s-or-2s/ 这道题有点和正常的思路不一样,不过挺好 Sort a linked list of 0s, 1s and 2s Given a linked list of 0s, 1s and 2s, sort it. Sour

martin_liang的专栏 511

Dify + mem0插件实战:如何让AI记住你的饮食习惯(附完整代码)

本文通过Dify平台与mem0插件实战,详细演示了如何为AI助手构建长期记忆系统,使其能记住并理解用户的复杂饮食习惯(如过敏源、饮食偏好)。文章提供了完整的工作流配置与Python代码示例,帮助开发者实现跨会话的个性化饮食建议,解决AI对话中的“健忘”问题。

lg888的博客 1103

最长值连续上升子序列

举例说明  2 1 3 4 5    最长值连续上升子序列为2 3 4 5  而不是最长连续(位置相邻)上升子序列 1 3 4 5 自己写了个码,但是超时了...   #include #include #include #include using namespace std; const int N=1e5+5; int a[N],dp[N]; int main() { int n

qq_39531685的博客 622

CentOS7全隔离环境部署Nvidia Tesla A100 40G驱动与CUDA工具包实战

本文详细介绍了在CentOS7全隔离环境下部署Nvidia Tesla A100 40G显卡驱动与CUDA工具包的实战经验。通过构建本地YUM仓库、解决驱动依赖问题以及三重验证法,确保Tesla A100与CUDA 11.7的完美兼容。同时分享了Anaconda3离线部署技巧,帮助用户在隔离环境中高效搭建Python GPU开发环境。

weixin_27215337的博客 407

21-CUDA扫描算法:前缀和并行实现 GPU编程入门

GPU并行前缀和计算:CUDA实现与优化 本文介绍了GPU上并行实现前缀和(扫描)算法的原理与优化方法。传统串行前缀和计算通过简单循环完成,而GPU并行算法采用"分而治之"策略,分为向上扫描(构建部分和树)和向下扫描(传播部分和)两个阶段。文章详细讲解了CUDA内核实现代码,包括全局内存和共享内存版本,并提供了性能优化技巧。通过利用GPU的并行计算能力,这种算法可以显著提高大规模数据前缀和的计算效率,是并行计算中的基础算法之一。

2301_79143213的博客 111

leetcode 673. Number of Longest Increasing Subsequence(最长递增子序列数量DP + BinarySearch)

Given an integer array nums, return the number of longest increasing subsequences. Notice that the sequence has to be strictly increasing. Example 1: Input: nums = [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequences are [1, 3, 4, 7]

蓝羽飞鸟的博客 280

使用CiteSpace软件对知网文献进行关键词共现/聚类/突现分析

一、基本概念CiteSpace(引文空间)是一款专注于分析科学分析中蕴含的潜在知识的软件。它是在科学计量学、数据可视化背景下逐渐发展起来的引文可视化分析软件。通过可视化的手段,CiteSpace能够呈现科学知识的结构、规律和分布情况,并因此将这种分析得到的可视化图形称为“科学知识图谱”。二、主要功能和用途知识图谱构建:根据科学文献的引用关系,CiteSpace可以生成知识图谱,帮助研究人员更好地理解学术领域中不同文献之间的联系和演化过程。主题聚类分析。

m0_64336780的博客 1万+

674. Longest Continuous Increasing Subsequence

Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). Example 1: Input: [1,3,5,4,7] Output: 3 Explanation: The longest continuous increasing sub...

sandrew0916的博客 107

YOLOv13涨点改进| CVPR 2026 |独家创新首发、主干改进篇 |利用RIS-PiDiNet主干让YOLOv13更加强大!适合遥感目标检测、小目标检测、旋转目标检测,变化检测,图像分割涨点

🔥本文提出了一种改进的RIS-PiDiNet主干网络,通过引入几何先验构建几何一致性检测器,显著提升了模型在任意方向、结构规则目标场景下的检测性能。包含两个核心模块:S-PDC利用极谐变换的谐波核建模目标结构对称性,RIS-PDC通过SO(2)群平均实现旋转不变性。网络采用基于RIS-block的主干结构并融合轻量级LBP特征,增强了细粒度结构表达能力。实验表明,该方法特别适用于遥感和复杂几何分布场景,能有效提升目标检测的鲁棒性和精度。文章还详细介绍了如何将RIS-PiDiNet集成到YOLOv13框架

Ai缝合怪、助力小伙伴高效发论文 91

Python爬虫实战:逆向工程与异步爬虫技术,高效抓取国家知识产权局专利数据

相比于传统的Selenium,Playwright由微软开发,支持多浏览器(Chromium, Firefox, WebKit),API更现代,执行速度更快,并且能轻松录制用户操作生成代码。通常,列表中的摘要信息是缩略的,我们需要进入每个专利的详情页获取完整信息(如主权要求、法律状态等)。我们的第一步是手动操作一遍搜索流程,并用Playwright的“录制”功能或开发者工具,找出真正返回专利数据的那一个或多个网络请求。以友好的、对人类行为模拟的方式爬取数据是基本的网络礼仪,也能有效避免你的IP被封锁。

2201_76125261的博客 2437

Longest Increasing Subsequence I/II

76. Longest Increasing Subsequence Tag: Dynamic Problem Main Idea: Classic DP Problem. Let  dp[i]\ dp[i] dp[i] represents the number of longest increasing subsequence at the position i. For ...

Zahb44856的博客 272

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

LeetCode 674. Longest Continuous Increasing Subsequence

问题描述Given an unsorted array of integers, find the length of longest continuous increasing subsequence. Example 1: Input: [1,3,5,4,7] Output: 3 Explanation: The longest continuous increasing subsequ

YXZreo的专栏 314

深度学习工具包 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")

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

LeetCode-Longest Continuous Increasing Subsequence

LeetCode Java Longest Continuous Increasing Subsequence

坟头草一米七五 274

674. Longest Continuous Increasing Subsequence。

Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).Example 1: Input: [1,3,5,4,7] Output: 3 Explanation: The longest continuous increasi

繁城落叶 585

LeetCode 674.Longest Continuous Increasing Subsequence

LeetCode 674.Longest Continuous Increasing SubsequenceDescription: Given an unsorted array of integers, find the length of longest continuous increasing subsequence. Example 1: Input: [1,3,5,4,7]

My Blog 252

第13周 Longest Continuous Increasing Subsequence

Longest Continuous Increasing SubsequenceLeetcode algorithms problem 674:Longest Continuous Increasing Subsequence 问题描述 Given an unsorted array of integers, find the length of longest continuous incr

m0_37856637的博客 261

leetcode 674. Longest Continuous Increasing Subsequence

1.题目Given an unsorted array of integers, find the length of longest continuous increasing subsequence. 给一个未排序的整型数组,寻找最长连续递增子序列的长度。 Example 1: Input: [1,3,5,4,7] Output: 3 Explanation: The longest

沐沐余风的专栏 630

LWC 49:674. Longest Continuous Increasing Subsequence

LWC 49:674. Longest Continuous Increasing Subsequence 详细代码可以fork下Github上leetcode项目,不定期更新。 从今天开始改变下刷题策略,Leetcode Weekly Contest中的每一题都单独更新,有些题还不再自己的能力范围之内,暂时不去解答,有能力独立AC后,再写解题报告。Problem: Given an uns

Demon-初来驾到 1128

leetcode刷题日记—— Longest Continuous Increasing Subsequence

Given an unsorted array of integers, find the length of longest continuous increasing subsequence. Example 1: Input: [1,3,5,4,7] Output: 3 Explanation: The longest continuous increasing subsequenc

cy_cn_2015的博客 477

DP-LeetCode674. 最长连续递增序列Longest Continuous Increasing Subsequence

1、题目描述 https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence/ 关键词:连续 给定一个未经排序的整数数组,找到最长且连续的的递增序列。 相似题:DP、二分-LeetCode300. 最长上升子序列LIS(可以不是连续的) https://blog.csdn.net/IOT_victor/article/details/105473256 2、代码详解 class Solution(obj

IOT_victor的博客 247

674-Longest Continuous Increasing Subsequence

难度:easy 类别:array1.题目描述Input: [1,3,5,4,7] Output: 3 Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. Even though [1,3,5,7] is also an increasing subsequence,

晨识草的博客 270
上一篇: Python string modify
下一篇: Binary bitwise operations
screaming
博客等级 码龄19年 61粉丝 6原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值