LintCode 1564: Interval Search (Binary Search 经典题)

PC-lint 9 + 中文手册 PCLINT是一种代码检查工具,还包括中文文档 立即下载

我的做法是对每个interval的start和end计数,如果是start, count++, end, count–。这里要注意点有重叠的情况。
用一个map来关联point和count。
用binary search来找小于或等于target的第一个数,如果对应的count==0, 说明target不在某interval,否则说明target在某interval。
代码如下:

class Solution {
public:
    /**
     * @param intervalList: 
     * @param number: 
     * @return: return True or False
     */
     
     
    string isInterval(vector<vector<int>> &intervalList, int number) {

        // <point, symbol>  symbol=1 is start of an interval, symbol==1 is the end of an interval
        map<int, int> mp; 
        int intervalCount = intervalList.size();
        
        int pointCount = intervalCount << 1;
        vector<int> points;
        
        for (int i = 0; i < intervalCount; ++i) {
            points.push_back(intervalList[i][0]);
            points.push_back(intervalList[i][1]);
            
            if (mp.find(intervalList[i][0]) != mp.end())
                mp[intervalList[i][0]] = 1;
            else
                mp[intervalList[i][0]]++;
                
            if (mp.find(intervalList[i][1]) != mp.end())
                mp[intervalList[i][1]] = -1;
            else
                mp[intervalList[i][1]]--; 
        }
    
        sort(points.begin(), points.end());
        int count = 0;
        map<int, int> mp2; //<point, count>
        for (int i = 0; i < pointCount; ++i) {
            count += mp[points[i]];
            mp2[points[i]] = count;   //count = 0 means no interval, count = 1 is a new interval of in the middle of an interval
        }
        
        int index = binarySearch(points, number); 

        if (mp2[points[index]] > 0) 
            return "True";
        else 
            return "False";
        
    }

private:
//find the position that is just smaller than or equal to number
    int binarySearch(vector<int> &nums, int target) {
        if (nums.size() == 0) return -1;
        int start = 0, end = nums.size() - 1;
        
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] < target) 
                start = mid;
            else if (nums[mid] > target)
                end = mid;
            else 
                return mid;
        }
        
        if (nums[end] == target) return end;
        
        return start;   
    }
    
};
GEO的工作原理,以及GEO会催生出更多的爬虫岗位吗? 摘要: GEO(生成式引擎优化)是提升内容在AI搜索(如ChatGPT、Perplexity等)中引用率的新策略,核心在于优化内容的可抓取性、语义清晰度、权威性。与传统SEO不同,GEO聚焦AI的引用逻辑,需通过爬虫监控AI回答、逆向分析引用源特征(如结构化数据、权威背书),并构建自动化工具优化内容。爬虫工程师需转型为“AI可见性基础设施构建者”,重点关注高权威站点、知识库及官方信息源,同时确保技术可抓取性(如放行AI爬虫UA)。GEO的核心是从“排名”转向“被AI引用”,强调实体识别与动态对话适配。 阅读详情

相关推荐

AMD显卡跑Ollama大模型?手把手教你搞定Windows下GPU识别与加速(以RX 9600XT为例)

本文详细指导如何在Windows系统下使用AMD显卡(如RX 9600XT)运行Ollama大模型,解决GPU识别与加速问题。通过获取非官方Ollama版本、替换ROCm库文件等步骤,实现高效的GPU加速推理,提升大语言模型的运行效率。

weixin_28707365的博客 511

Leetcode 1564 把箱子放进仓库里1

Leetcode 1564 把箱子放进仓库里1 题目描述:给定两个正整数数组 boxes 和 warehouse ,分别包含单位宽度的箱子的高度,以及仓库中 n 个房间各自的高度。仓库的房间分别从 0 到 n - 1 自左向右编号, warehouse[i] (索引从 0 开始)是第 i 个房间的高度。 箱子放进仓库时遵循下列规则: 箱子不可叠放。 你可以重新调整箱子的顺序。 箱子只能从左向右推进仓库中。 如果仓库中某房间的高度小于某箱子的高度,则这个箱子和之后的箱子都会停在这个房间的前面。 你最多可以在仓

qq_42791848的博客 1142

全格式动态线性化下无模型自适应控制原理与matlab程序

摘要:本文研究全格式动态线性化(FFDL)下的无模型自适应控制方法。针对单输入单输出非线性系统,FFDL通过同时利用固定窗口内的输入和输出变化量构建线性数据模型,相比紧格式和偏格式动态线性化具有更强的非线性逼近能力。文中采用带可变遗忘因子的投影算法更新伪梯度向量,并设计一步前向加权控制器。通过MATLAB仿真验证,选取Ly=2、Lu=3的参数配置,FFDL-MFAC方法在强非线性系统中表现出良好的跟踪性能和稳定性,系统误差显著减小。结果表明该方法适用于存在滞后和强非线性耦合的复杂系统控制。

loveyy0921的博客 1219

区间树 INTERVAL-SEARCH

本文讨论 INTERVAL-SEARCH 算法的正确性,算法如下: INTERVAL-SEARCH(T, i) x = T.root while x != T.nil and I does not overlap x.int if x.left != T.nil and x.left.max >= i.low x = x.left else x = x.right 仅讨论 循环中的代码 1、x.left == T.nil 左子树为空...

weixin_44671399的博客 337

避坑指南:企业微信IP白名单设置失败的5种常见原因及解决方案

本文深入解析企业微信API调用中IP白名单设置失败的5种常见原因,包括动态公网IP变更、代理服务器导致的IP失真等,并提供针对性的解决方案。特别针对可信IP配置问题,详细介绍了诊断方法和Java代码示例,帮助企业开发者快速解决访问限制问题,确保API调用安全稳定。

weixin_29280657的博客 632

CTF实战:手把手教你用Python破解转轮机加密(附完整脚本)

本文详细介绍了如何使用Python逆向破解转轮机加密,特别针对CTF比赛中的Crypto类题目。通过解析转轮机加密原理、实战Python脚本编写及调试技巧,帮助参赛者快速掌握破解方法,提升在攻防世界等CTF比赛中的解题效率。

silver的专栏 1130

《算法导论3rd第十四章》数据结构扩张

算法导论,十四章,数据结构扩张。即如果通过附加属性使用基础数据结构满足各种需求

懒猫的脚印 1148

【数学建模】编程手学习路线

在学习过程中,建议注重理论与实践相结合,多进行实例练习和项目实践,以巩固所学知识并提升实际应用能力。同时,保持对新技术和新方法的关注和学习,不断提升自己的专业素养和竞争力。NumPy、Pandas、Matplotlib和Seaborn等库是数据处理和可视化的重要工具。掌握常用机器学习算法的原理和应用,如决策树、支持向量机、神经网络等。学习内容包括微积分、线性方程组、矩阵运算、概率分布、统计推断等。学习内容包括基本语法、函数和模块、面向对象编程、文件操作等。深入了解优化理论和方法,如梯度下降法、牛顿法等。

2301_79586491的博客 2975

区间树上的重叠区间查找算法——C++

区间树上的重叠区间查找算法——C++ 题目: 区间树的构造; 查找算法Interval-Search(T, i); 算法设计:      步骤一:区间树是在红黑树基础上进行的简单的数据结构扩张。选择一棵红黑树,在每个结点x中加入一个区间属性x.int,设置x的关键字为区间的低端点x.int.low。      步骤二:附加信息。附加的信息为x.max,其值为以x为根的子树中所有区间的端点...

狒狒不会编程 1935

硬件开发实践:高速 PCB 差分信号与时钟同步优化

由两条互补信号线组成(正负极)接收端只关注两线之间电压差共模噪声对两线同时作用,可被抵消。

2501_93174775的博客 405

新手3dslicer手动肝脏切割及体积测量(详细图文)

刚接手软件的时候,我一直想用自动分割工具,试验了Med sam,依赖安装不了;试验了英伟达的AI,NvidiaAIAssis,传服务器根本没反应,所有只有用了手动切割。不要求所有层面勾画,但是最好是典型层面都勾画一下,特别是有毗邻脏器密度相近的层面。点击3D后可能三维窗口未显示,可以调整一下窗口大小,有可能显示在我们看见的范围之外。早就准备更新这篇了,由于懒癌发作,一直早葛优躺,今天刚好有点时间,就简单写下来。

linjianping513的博客 5957

用等步长分割法(Equal Interval Search Method)求函数最大值的Python程序

代码: 求函数A = 4*sinx *(1+cosx) 的最大值(x是角度) x的范围是0~90° 迭代到误差小于10^-6为止 from sympy import * a = 0 b = 90 dx = 0.05 x = symbols('x') def func(x): A = 4*sin(x*pi.evalf()/180)*(1+cos(x*pi.evalf()/180)) return A A_list = [] i = 0 while True: i += 1 x

Fo*(Bi)的博客 1455

本地Pycharm连接远程服务器详细配置过程(直接在本地使用服务器显卡,很棒)

相信很多人都遇见过这种情况:实验室成员使用同一台服务器,每个人拥有自己的独立账号,我们可以使用服务器更好的配置完成实验,毕竟自己哪有money拥有自己的3090呢。

NorthSmile的博客 4万+

菜鸟到高手之 - Binary Search,half-interval search(二分查找,折半查找)

For binary search, the array should be arranged in ascending or descending order. A binary search halves the number of items to check with each iteration, so locating an item (or determining its absenc

Bruce1634的专栏 850

Devexpress16.2.6破解工具

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

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

区间树简单实现(interval_tree)

interval_tree.cpp /* 区间树(interval tree)是一种对动态集合进行维护的扩张红黑树,因此可在实验二红黑树的基础上进行扩张。 */ #include #include #include #include #include #include #define SENTINEL -100000 //哨兵,作为nil结点的key,方便树状输出时临

hubi0952的专栏 5905

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

算法导论——区间树上的重叠区间查找算法

一、   算法设计与分析: (1)   数据结构设计: //区间 struct Interval{ int low; int high; }; //节点 struct Node{ Node(int low,int high){ this->key=low; this->Int.low=low; this

xiaowang627的博客 2288

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

二分法-二分查找的应用及三个经典例题

二分法-二分查找应用及例题在ICPC-ACM竞赛中,二分法是一种常用的解题策略,其中二分搜索是应用非常广泛的一种,主要使用的有STL中的binary_search()函数、lower_bound()函数、upper_bound()函数,这些函数一般要配合sort()、unique()函数使用。1. binary_search(begin,end,index):在数组中,若找到index则返回1,找不

? 1万+

区间树查找算法

一、题目    题目:区间树查找算法   实验目的:实现有效的区间树查找算法 二、算法思想 1、基本概念: 区间:一个事件占用的时间 闭区间:实数的有序对[t1,t2],使t1≤t2 区间的对象表示:[t1,t2]可以用对象i表示,有两个属性: low[i]=t1//起点或低点 high[i]=t2//终点或高点 区间的重叠:i∩i’≠Ø ⇔(low[i]≤high[i

码小农 7189

使用PC-lint

PC-lint的使用网络上有很多,下一篇将会转载一下。这里主要记录一下在使用的过程中所遇到的问题。1.错误如下-- Module:   d:/Projects/magellan/main/code/magellan/MgAIAction.cpp      (C++)      #include "co-msc80.h" /* generated from -header(co-msc80.

Jacky Li的专栏 5940

二分查找(Binary Search) 常见问题解决方法总结

缘由今天浏览 何登成的技术博客  无意中发现了写的blog,二分查找(Binary Search)需要注意的问题,以及在数据库内核中的实现。随想总结下二分查找的常见问题。问题背景今年的实习生招聘考试,我出了一道二分查找(Binary Search)的题目。题目大意如下:给定一个升序排列的自然数数组,数组中包含重复数字,例如:[1,2,2,3,4,4,4,5,6,7,7]。问题:给定任意自然数,对数...

Daniel 的技术笔记 不积跬步无以至千里,不积小流无以成江海。 1万+

Linux内核中使用红黑树的扩展特性实现区间树(Interval tree)

原文地址:http://galex.cn/linux%E5%86%85%E6%A0%B8%E4%B8%AD%E4%BD%BF%E7%94%A8%E7%BA%A2%E9%BB%91%E6%A0%91%E7%9A%84%E6%89%A9%E5%B1%95%E7%89%B9%E6%80%A7%E5%AE%9E%E7%8E%B0%E5%8C%BA%E9%97%B4%E6%A0%91%EF%BC%88int

雜貨鋪 2310

Binary Search 二分法查找的三个模板

Parts of a Successful Binary Search Binary Search is generally composed of 3 main sections: Pre-processing - Sort if collection is unsorted. Binary Search - Using a loop or recursion to divid...

南方以北 4545

【算法实验一】--A题--【分治法】--二分查找

1001.二分查找 时限:1000ms 内存限制:10000K  总时限:3000ms 描述 给定一个单调递增的整数序列,问某个整数是否在序列中。   输入 第一行为一个整数n,表示序列中整数的个数;第二行为n(n不超过10000)个整数;第三行为一个整数m(m不超过50000),表示查询的个数;接下来m行每行一个整数k。   输出 每个查询的输出占一行,如果k在序列中,输出Ye...

杨的博客 1090

Week 5.2 | BST的几何应用 | Princeton Algorithms

文章目录一、基本BST的应用1. 1-d range search2. 线段交点二、kd-trees1. 2-d range search2. 2-d 最近点搜索3. kd-tree三、interval search trees1. 定义2. 实现3. 复杂度4. 区间搜索树的应用: 矩形相交四、总结 一、基本BST的应用 1. 1-d range search 目标 在有序symbol table中扩展实现两个操作: · Range search: find all keys between k1 a

qq_46497008的博客 539

数据结构 树 例题 Complete Binary Search Tree

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys less than the node’s key. The right su

一木 828

算法——二分法查找(binarySearch)

二分法查找,也称为折半法,是一种在有序数组中查找特定元素的搜索算法。二分法查找的思路如下:(1)首先,从数组的中间元素开始搜索,如果该元素正好是目标元素,则搜索过程结束,否则执行下一步。(2)如果目标元素大于/小于中间元素,则在数组大于/小于中间元素的那一半区域查找,然后重复步骤(1)的操作。(3)如果某一步数组为空,则表示找不到目标元素。二分法查找的时间复杂度O(logn)。非递归算法:func...

u012194956的博客 17万+
上一篇: LintCode 1565: Modern Ludo I (DP典型题)
下一篇: LintCode 1479: Can Reach The Endpoint (BFS 典型题)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址