LeetCode From Easy To Hard No7[Medium]: Print Zero Even Odd 按顺序打印[010203...0n]

流媒体影视爆款预测数据集6000部剧集电影21特征 本数据集模拟流媒体平台影视内容特征,包含6000部剧集、电影与纪录片样本、21个字段,覆盖内容类型、题材、出品国家、上映年份与月份、内容分级、是否平台原创、是否系列续集、改编来源、时长、季数、明星影响力、制作与营销预算、观众评分、社交热度等维度。提供top10_hit分类目标(进入平台榜单前十并保持4周以上)与views_28d_m回归目标(上线28天观看量),结果字段独立分离,便于练习避免目标泄漏。数据干净完整、无缺失值、无需表关联,直接可用于分类、回归、探索性分析,以及发布档期选择、题材与续集表现、单位营销成本观看效率等研究,适合影视行业分析、推荐系统与机器学习教学。说明:本数据为Python生成的合成数据,仅反映生成规则,不含真实节目与个人信息。许可:CC0公有领域,可自由使用与二次分发。 立即下载

第一次挑战Medium的题:

Suppose you are given the following code:

class ZeroEvenOdd {
  public ZeroEvenOdd(int n) { ... }      // constructor
  public void zero(printNumber) { ... }  // only output 0's
  public void even(printNumber) { ... }  // only output even numbers
  public void odd(printNumber) { ... }   // only output odd numbers
}

The same instance of ZeroEvenOdd will be passed to three different threads:

  1. Thread A will call zero() which should only output 0's.
  2. Thread B will call even() which should only ouput even numbers.
  3. Thread C will call odd() which should only output odd numbers.

Each of the thread is given a printNumber method to output an integer. Modify the given program to output the series 010203040506... where the length of the series must be 2n.

 

Example 1:

Input: n = 2
Output: "0102"
Explanation: There are three threads being fired asynchronously. One of them calls zero(), the other calls even(), and the last one calls odd(). "0102" is the correct output.

Example 2:

Input: n = 5
Output: "0102030405"

意思就是要我们输出【0102030405...0n】

之前学会了使用Semaphore,刚好这道题可以用得上:

import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;

class ZeroEvenOdd {

    private int n;

    Semaphore zeroLock, oddLock, evenLock;

    public ZeroEvenOdd(int n) {
        this.n = n;
        this.zeroLock = new Semaphore(1);
        this.oddLock = new Semaphore(0);
        this.evenLock = new Semaphore(0);
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        int mark = 0;
        while (mark < n) {
            zeroLock.acquire();
            printNumber.accept(0);
            mark ++;
            if (mark % 2 == 0) {
                evenLock.release();
            } else {
                oddLock.release();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        int even = 2;
        while (even <= n) {
            evenLock.acquire();
            printNumber.accept(even);
            even += 2;
            zeroLock.release();
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        int odd = 1;
        while (odd <= n) {
            oddLock.acquire();
            printNumber.accept(odd);
            odd +=2;
            zeroLock.release();
        }
    }
}

 

AI大模型安全架构落地解决方案.pptx 立即下载

相关推荐

国央企创新负责人如何提升企业创新与技术合作的精准度?.docx

国央企创新负责人如何提升企业创新与技术合作的精准度?

多线程-打印零和奇偶数

打印零和奇偶数 要求 假设有这么一个类: class ZeroEvenOdd { public ZeroEvenOdd(int n) { ... } // 构造函数 public void zero(printNumber) { ... } // 仅打印出 0 public void even(printNumber) { ... } // 仅打印出 偶数 public void odd(printNumber) { ... } // 仅打印出 奇数 } 相同的一个 Ze

u012750235的博客 878

科技中介服务机构在协助企业对接科研成果时,如何提升服务响应速度与专业化水平.docx

科技中介服务机构在协助企业对接科研成果时,如何提升服务响应速度与专业化水平

两个线程一个打印1,一个打印2,要求循环打印1212121212

两个线程一个打印1,一个打印2,要求循环打印121212方法1:分析问题两个线程,可以想到的是多线程编程,共享变量,数据等,设想先让一个线程打印1,然后处于等待(wait)状态,接着另一个线程打印2,然后唤醒(notify)线程1,线程2再进入等待(wait)状态,线程1被唤醒后接着打印1,依次循环输出即可代码public class Test { static final Object ...

libinbin147256369的博客 2860

高校技术转移办公室人员如何利用智能工具简化技术成果的推介与转化流程?.docx

科易网基于AI模型+行业大数据,在技术转移、成果转化、技术经纪、知识产权、产业创新、科技招商等垂直领域的多样化应用场景,推出科技创新领域的AI+工具与数智化解决方案,推动科技创新与产业创新智能化发展。

solong 图像处理器 - v3.4 - 吾爱大佬 by 金牌软件 .exe

solong 图像处理器 _ v3.4 _ 吾爱大佬 by 金牌软件 .exe

[LeetCode] 1116. Print Zero Even Odd

Suppose you are given the following code: class ZeroEvenOdd { public ZeroEvenOdd(int n) { ... } // constructor public void zero(printNumber) { ... } // only output 0's public void even(p...

liuwenyou的博客 656

西门子 S7 PLC 对接 MES 系统:HTTP/JSON 通信实施指南

内容概要:本文介绍了通过IGT-DSER智能网关实现西门子S7-1500 PLC(采用优化访问DB数据块)与MES系统的对接方案。重点阐述了使用S7-PLUS标签方式读取PLC变量标签数据,结合网关边缘处理能力进行数据换算与JSON封装,并通过HTTP/GET或POST方式将数据上传至MES系统的技术路径。文中详细说明了网络配置、变量映射、触发逻辑设置、JSON结构生成、联调验收流程及常见故障排查方法,强调无需修改PLC程序即可完成集成,适用于工业现场快速部署。; 适合人群:自动化工程师、MES实施工程师、工业网络与设备运维人员; 使用场景及目标:①实现西门子S7-1500等支持优化DB的PLC与MES系统高效对接;②在不改动原有PLC程序的前提下完成数据采集与上传;③通过标准化JSON格式与HTTP协议实现与各类业务平台的数据交互;④提升系统集成效率并确保数据传输的准确性与可监控性; 阅读建议:此资源以实际工程案例为基础,建议读者结合IGT-DSER网关参数管理软件操作实践,重点关注标签配置、触发条件设定与JSON字段映射的细节,并在测试环境中验证请求与响应闭环后再投入正式运行。

1116. Print Zero Even Odd

Suppose you are given the following code: class ZeroEvenOdd { public ZeroEvenOdd(int n) { ... } // constructor public void zero(printNumber) { ... } // only output 0's public void even(pr...

Umbrella Corporation 6599

PSIM-串联谐振半桥LLC开关电源+PFM变频闭环控制【仿真+计算书+参考文献】

内容概要:本文详细介绍了PSIM-串联谐振半桥LLC开关电源结合PFM变频闭环控制的设计与仿真,系统阐述了LLC谐振变换器的建模方法、软开关实现机制及基于变频控制的闭环调节策略。资源包涵盖完整的PSIM仿真模型、详细的计算书与参考文献,重点展示了在宽负载范围内通过调节开关频率实现高效能运行的技术路径。系统利用串联谐振腔的频率特性,在不同负载条件下实现零电压开通(ZVS)或零电流关断(ZCS),显著降低开关损耗;同时,闭环控制通过反馈输出电压动态调整工作频率,确保输出稳定性和动态响应性能。该设计特别适用于对高效率、高功率密度有严格要求的应用场景。; 适合人群:具备电力电子、电源设计或自动化相关背景的本科高年级学生、研究生及从事开关电源研发的工程师。; 使用场景及目标:①掌握LLC谐振变换器的工作原理及其在PSIM中的建模与仿真方法;②学习PFM(脉冲频率调制)变频控制在开关电源中的闭环实现技术;③应用于高频高效电源系统的设计与优化,如通信电源、新能源变换器、车载充电机等;④为科研项目或毕业设计提供完整的仿真参考、计算依据与技术支持。; 阅读建议:建议读者结合提供的PSIM仿真文件、计算书与参考文献同步操作,深入理解谐振参数设计、变频控制逻辑与闭环反馈的实现细节,重点关注开关频率与增益曲线的关系、谐振元件参数匹配对效率的影响,并通过改变输入电压和负载条件验证系统的稳态与动态性能表现。

SageMath下载与安装

SageMath的下载与安装

旺旺的碎冰冰~的博客 7509

LeetCode刷题笔记 - 1116. 打印零与奇偶数(多线程)

强烈推荐:LeetCode刷题笔记 文章目录题目Code 1 : 信号量法 题目 假设有这么一个类: class ZeroEvenOdd { public ZeroEvenOdd(int n) { ... } // 构造函数 public void zero(printNumber) { ... } // 仅打印出 0 public void even(printNumb...

越看越喜欢啊 1328

QCC5125/QCC5144----LDAC 44.1K 48K 96K 192K 输出

QCC5125/QCC5144----LDAC 44.1K 48K 96K 192K 输出。而且还不需要license限制。

Alex_886的博客 1977

线程方面

线程从创建、运行到结束有五个状态:新生状态、就绪状态、运行状态、阻塞状态及死亡状态。 java中每个对象都有一个内置锁。 当程序运行到非静态的synchronized同步方法上时,自动获得与正在执行代码类的当前实例(this实例)有关的锁。获得一个对象的锁也称为获取锁、锁定对象、在对象上锁定或在对象上同步。 当程序运行到synchronized同步方法或代码块时该对象锁才起作用。

lyn789的博客 439

ADS新手必看:5分钟搞定Smith圆图阻抗匹配(附详细操作截图)

本文为射频电路设计新手提供了在ADS软件中快速使用Smith圆图进行阻抗匹配的实战指南。通过清晰的步骤和操作截图,详细演示了如何从负载阻抗点出发,通过添加电感和电容元件,在5分钟内完成向50欧姆标准阻抗的匹配,并介绍了仿真验证与性能调优的方法,帮助工程师和学生直观掌握这一核心技能。

weixin_29261711的博客 394

VPS环境搭建及配置

VPS(Virtual Private Server)是一种虚拟化技术,可以将一台物理服务器分成多个虚拟服务器,每个虚拟服务器都有独立的操作系统和资源,相互之间互不影响。VPS可以提供类似于独立服务器的功能,但价格更便宜,适合中小企业和个人用户使用。VPS可以用于网站托管、应用程序部署、游戏服务器、数据备份等各种场景。

YJ_12340的博客 1万+

按序打印

按序打印 一开始这样写的,错了,大家知道为什么吗? class Foo { private int volatile n = 0; public Foo() { } public void first(Runnable printFirst) throws InterruptedException { synchronized (this){ if(n % 3 == 0){ // pri

沐雨金鳞 466

Avellaneda & Stoikov模型实战解析:如何动态调整做市策略参数

本文深入解析Avellaneda & Stoikov模型在动态调整做市策略参数中的应用,重点探讨库存状态、剩余时间、风险系数和订单深度等核心参数的实战技巧。通过加密货币市场的实际案例,展示如何根据市场波动和流动性动态调整参数,提升做市策略的盈利能力和风险控制水平。

weixin_29070861的博客 203

[Java]LeetCode1116. 打印零与奇偶数 | Print Zero Even Odd

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址:➤如果链接不是山青咏芝的博客园地址,则可能是爬取...

weixin_30314631的博客 445

告别信号毛刺!手把手教你用ADS和IBIS-AMI模型搞定PCIe Gen3眼图仿真

本文详细介绍了如何使用Keysight ADS和IBIS-AMI模型进行PCIe Gen3眼图仿真,解决高速信号传输中的信号质量问题。从仿真环境搭建、S参数预处理到眼图优化与故障排除,提供了一套完整的工程实践指南,帮助工程师提升PCIe Gen3接口的信号完整性。

weixin_28366053的博客 371

IC 笔试真题之吾见——华为实习(1)

前言 今天(2022 04 07)刚建立了一个专栏《IC真题之吾见》,准备记录一些IC真题的见解,为以后找工作做一点准备。 刷题绝不是目的,以题代练,以题代学。 题目来自师兄申请 华为实习“设计”岗位 的笔试真题。 见解大部分来自自己学习的理解,也有部分超纲知识是网络检索得到,希望可以多多在评论区留言交流,共同进步! 有问题的地方也希望可以直接批评指正! 后面也会同步更新此专栏! 1、下列有关时序分析的描述正确的是() A. recovery时间,是指异步控制信号在有效时钟沿到达之后必须保持

记录所学,分享知识,结识挚友 8637

printf打印数字_面试题实战:给一个数 n,使用 Go 打印交替顺序零与奇偶数

点击上方蓝色“Go语言中文网”关注我们,领全套Go资料,每天学习Go语言这是我写的第三题 LeetCode Concurrency(并发) Go 语言详解,技术比前面两题都要复杂。为了解释到我自认够清楚,写的时间多花了好几倍(1x = 2hr)。本题 LeetCode 链接: https://leetcode.com/problems/print-zero-even-odd/本题题目...

weixin_39633102的博客 235

6-Halcon-- var_threshold 函数功能(用于基于局部统计特性的动态阈值分割的算子)

var_threshold 是 HALCON 中用于基于局部统计特性的动态阈值分割的算子,特别适用于处理低对比度图像或纹理均匀但包含细微差异的场景。与 dyn_threshold 不同,它不依赖预处理生成的参考图像,而是直接在局部区域内计算灰度值的统计特性(均值和标准差),从而自适应调整阈值。

weixin_45590420的博客 1328

LeetCode 1116. Print Zero Even Odd

Description: Suppose you are given the following code: class ZeroEvenOdd { public ZeroEvenOdd(int n) { … } // constructor public void zero(printNumber) { … } // only output 0’s public void even(printNumber) { … } // only output even numbers public v

村里的原振侠的博客 392

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

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

java 多线程刷题(LeetCode-1114. 按序打印)

java多线程,volatile关键字

越看越喜欢啊 1106

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

上一篇: LeetCode From Easy To Hard No6[Easy]: Print in Order 按顺序执行线程
下一篇: LeetCode From Easy To Hard No8[Easy]: Squares of a Sorted Array
我属码
博客等级 码龄10年 2粉丝 17原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值