Leetcode2389. 和有限的最长子序列

基于PSO-BP神经网络的风电功率预测研究论文复现 风电功率预测。基于PSO-BP神经网络的风电功率预测论文复现。matlab程序,注释清晰。 阅读详情

Every day a Leetcode

题目来源:2389. 和有限的最长子序列

解法1:排序+贪心

由题意可知, nums 的元素次序对结果无影响,因此我们对 nums 从小到大进行排序。

基于贪心的思想,和有限的最长子序列由最小的前几个数组成。

遍历 queries,假设当前查询值为 q。

对于每个查询值 q,初始化和 sum=0,从头开始遍历排序后的 nums 数组,sum 累加 nums[i] 直至 sum>q 或者遍历完数组 nums,最后更新 answer 数组。

遍历完 queries,answer 数组即为答案。

代码:

/*
 * @lc app=leetcode.cn id=2389 lang=cpp
 *
 * [2389] 和有限的最长子序列
 */

// @lc code=start
class Solution
{
public:
    vector<int> answerQueries(vector<int> &nums, vector<int> &queries)
    {
        int n = nums.size();
        int m = queries.size();
        sort(nums.begin(), nums.end());
        vector<int> answer(m);
        for (int i = 0; i < m; i++)
        {
            int sum = 0;
            int count = 0;
            int index = 0;
            while (index < n && sum <= queries[i])
            {
                sum += nums[index];
                index++;
                if (sum <= queries[i])
                    count++;
            }
            answer[i] = count;
        }
        return answer;
    }
};
// @lc code=end

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(n*(logn+m)),其中 n 是数组 nums 的长度,m 是数组 queries 的长度。对 nums 进行排序需要 O(nlogn) 的时间。

空间复杂度:O(1),我们只使用了常数个变量。返回值不计入空间复杂度。

24 SAP CPI 调用SAP HTTP接口 SAP CPI 调用SAP HTTP接口 阅读详情

相关推荐

劳特巴赫 Trace32 调试使用教程

详细介绍如何使用trace32进行调试

m0_56208280的博客 4万+

【2389. 和有限的最长子序列】

2389. 和有限的最长子序列

Sugar_wolf的博客 696

ROS TF坐标转换实战:从零搭建机器人坐标系(附常见问题排查)

本文提供了一份ROS TF坐标转换的实战指南,详细讲解了如何从零为机器人搭建完整的坐标系,并深入解析了TF的原理。内容涵盖静态与动态坐标变换的发布、URDF模型使用、以及Rviz和rqt_tf_tree等可视化调试工具。文章还附带了常见问题排查表,帮助开发者快速定位并解决TF树断裂、数据错位等典型问题。

weixin_29268385的博客 206

LeetCode——2389. 和有限的最长子序列

LeetCode——2389. 和有限的最长子序列

玄昌盛不会编程 218

【CTFWP】ctfshow-web40

CTFWP:ctfshow-web40

LongL_GuYu的博客 1863

用Codex自动化挖掘电梯行业外贸客户:从关键词到22维深度分析

在B2B外贸客户开发中,精准定位垂直行业潜在客户是核心挑战。传统手动搜索效率低下,而数据驱动的工作流正成为解决方案。其原理在于将模糊的业务需求转化为机器可识别的结构化查询,通过组合行业核心关键词(如“Elevator Manufacturer”、“Elevator Maintenance”)与商业角色描述,系统性地从海量数据中筛选目标。这种自动化抓取技术的价值在于,它不仅生成客户名单,更通过多维数据分析(如公司规模、业务标签、数字足迹)构建初步的客户画像,为后续的优先级排序和个性化触达提供情报基础。在工业制

weixin_34054866的博客 455

【每日一题】- 和有限的最长子序列

Problem: 2389. 和有限的最长子序列 暴力求解

xuedong_1989的博客 218

等保2.0下可信验证的动态实现与合规实践

本文深入解读等保2.0标准中的“可信验证”要求,并重点探讨其动态实现与合规实践。文章阐述了从可信根、信任链到动态验证的核心概念,拆解了不同安全等级的实施差异,并提供了从硬件选型、软件赋能到平台集成的四步落地指南。通过行业案例与避坑心得,为构建覆盖计算环境、区域边界、通信网络和安全管理中心的全链条可信防御体系提供了实用参考。

d3e4f的博客 829

最长公共子序列、最长连续公共子序列、最长递增子序列

面试中除了排序问题,还会经常出现字符串的子序列问题,这里讲解使用动态规划解决三个常见的子序列问题: 1、最长公共子序列问题(LCS,longest-common-subsequence problem) 2、最长连续公共子序列问题 3、最长递增子序列(LIS,longest-increment-subsequence) 最长公共子序列问题LCS 问题描述: 给定两个序列X=&l...

Irving_zhang的专栏 1万+

【电机应用控制】——直流有刷电机&驱动板/编码器介绍&PID算法&实操代码思路

声明:学习笔记来自正点原子B站教程,仅供学习交流!!玩具车、平衡车、无人机、印刷机、打印机、手机振动马达等电机即电动机(motor),也叫作马达,电能转化为机械能。按电源:直流、交流按用途:驱动用、控制用按运转速度:高速、低速、恒速、调速直流电机(有刷、无刷)、舵机、步进电机、伺服电机1、直流有刷电机(Brushed DC Motor,简称BDC)是内含电刷装置的将直流电能转化为机械能的电动机。例如四驱赛车四个马达操控方便、成本低、维护时换电刷即可;

weixin_51658186的博客 2万+

11、CUDA 内存优化:平铺矩阵乘法技术解析

本文深入解析了CUDA中的平铺矩阵乘法技术,重点介绍了如何利用共享内存和线程协作减少全局内存访问,提升计算效率。通过矩阵乘法实例,详细阐述了平铺算法的执行流程、内核代码实现及性能优化策略,包括平铺大小选择、线程同步机制和代码优化建议。文章还分析了该技术在深度学习、图像处理和科学计算等领域的应用价值,为CUDA程序的内存优化提供了系统性指导。

peace的博客 72

2389. 和有限的最长子序列

把数组由小到大排序,然后累加和(num[n] = sum(num[0]…num[n])),如果恰好大于这个和,下标就是答案。直接进行二分查找,减少查询复杂度。给二个数组,第一个数组里面的最多元素的子序列和小于第二个数组的每一个数的集合。

luckycoding的专栏 133

[系统安全] 四十七.恶意软件分析 (3)动态分析经典沙箱Cape的安装和基础用法详解

系统安全将更好地帮助初学者了解病毒逆向分析和系统安全。前文详细介绍恶意代码静态分析经典工具Capa的基础用法,以及批量提取静态特征和ATT&CK技战术,主要是从提取的静态特征Json文件中提取关键特征。这篇文章将详细讲解动态分析沙箱Cape,其是一个开源的自动恶意软件分析系统,通过自动运行和分析恶意软件,全面分析和提取恶意软件的关键特征。本文先介绍Cape沙箱的安装和基础用法,后续随着深入再分享。基础性文章,希望对您有帮助!

杨秀璋的专栏 6739

【刷题之路】LeetCode 2389. 和有限的最长子序列

时间复杂度:O((n+m)logn),其中n为数组nums的长度,m为数组queries的长度,对数组nums进行排序的复杂度为nlogn,二分查找的复杂度为logn,故总的时间复杂度为O((n+m)logn)。返回一个长度为 m 的数组 answer ,其中 answer[i] 是 nums 中 元素之和小于等于 queries[i] 的 子序列 的 最大 长度。由题目描述我们可知,对于每个queries[i],我们都需要找到一个子序列,使得该子序列的元素之和不超过queries[i],

kk702392702的博客 671

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

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

力扣_2389. 和有限的最长子序列

力扣_2389. 和有限的最长子序列 给你一个长度为 `n` 的整数数组 `nums` ,和一个长度为 `m` 的整数数组 `queries` 。 返回一个长度为 `m` 的数组 `answer` ,其中 `answer[i]` 是 `nums` 中 元素之和小于等于 `queries[i]` 的 **子序列** 的 **最大** 长度 。

seabirdssss的博客 291

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

力扣2389.和有限的最长子序列

排序 + 前缀和二分。

Pisasama的博客 346

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

力扣(LeetCode)2389. 和有限的最长子序列(C++)

【墨染】确定贪心思路,解题的一半。

墨染 440

LeetCode 2389. 和有限的最长子序列

给你一个长度为n的整数数组nums,和一个长度为m的整数数组queries。返回一个长度为m的数组answer,其中answer[i]是nums中 元素之和小于等于queries[i]的的长度。是由一个数组删除某些元素(也可以不删除)但不改变剩余元素顺序得到的一个数组。[2,3,4]queries 对应的 answer 如下:- 子序列 [2,1] 的和小于或等于 3。可以证明满足题目要求的子序列的最大长度是 2 ,所以 answer[0] = 2。

m0_56090828的博客 829

python-leetcode-2389. 和有限的最长子序列

可以使用来解决这个问题。

Lucy_wzw的博客 235

Leetcode.2389 和有限的最长子序列

排序 + 二分

感觉画质不如...原神的博客 685

LeetCode 2389.和有限的最长子序列

返回一个长度为 m 的数组 answer ,其中 answer[i] 是 nums 中 元素之和小于等于 queries[i] 的 子序列 的 最大 长度。如果nums的长度为n,queries的长度为m,则此算法时间复杂度为O((n+m)logn),空间复杂度为O(n)。输入:nums = [4,5,2,1], queries = [3,10,21]输入:nums = [2,3,4,5], queries = [1]输出:[2,3,4]

tus00000的博客 310

Leetcode 2389. 和有限的最长子序列

返回一个长度为 m 的数组 answer ,其中 answer[i] 是 nums 中 元素之和小于等于 queries[i] 的 子序列 的 最大 长度。最长的子序列长度一定是最小的k个元素组成的序列,所以可以先升序排列nums,然后贪心的取前面的元素和。给你一个长度为 n 的整数数组 nums ,和一个长度为 m 的整数数组 queries。子序列 是由一个数组删除某些元素(也可以不删除)但不改变剩余元素顺序得到的一个数组。

m0_51437455的博客 304

力扣2389,和有限的最长子序列

ower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。输入:nums = [4,5,2,1], queries = [3,10,21]输入:nums = [2,3,4,5], queries = [1]输出:[2,3,4]

vcoy的博客 423

Java 和有限的最长子序列 力扣2389

如示例1,nums排好后是1,2,4,5,从nums的第一位开始相加,直到超过数组queries中的第 i 位,相加时要统计相加的次数,该次数就是数组answer的第 i 位数值。1+2+4>3, 结束本次循环,满足要求的子序列最大长度就是2,answer[0]就是2。- 子序列 [4,5,2,1] 的和小于或等于 21。可以证明满足题目要求的子序列的最大长度是 3 ,所以 answer[1] = 3。可以证明满足题目要求的子序列的最大长度是 2 ,所以 answer[0] = 2。

XinxingZh的博客 144
上一篇: Leetcode2404. 出现最频繁的偶数元素
下一篇: Leetcode2383. 赢得比赛需要的最少训练时长
UestcXiye
博客等级 码龄8年 9032粉丝 1306原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值