Binary Search Comprehension

字符串编程全解析:从基础操作到KMP算法与动态规划实战 字符串作为编程中最基础的数据结构,其不可变性和编码特性决定了处理方式的独特性。理解字符串的基本原理,如索引访问、切片操作和编码转换,是掌握高效处理技术的前提。在算法层面,KMP算法通过构建部分匹配表优化模式查找,而动态规划则能有效解决最长公共子序列等复杂问题。这些技术的工程价值在于提升程序性能和解决实际问题,广泛应用于文本处理、数据分析和搜索引擎等场景。本文聚焦字符串处理的核心难点,通过KMP算法和动态规划等热词技术,系统讲解从基础到高级的字符串编程实战方法。 阅读详情

Binary Search is a popular topic in coding assessments. However, there are tons of variations of binary search, and it is sometimes really confusing. Today, I want to clarify several variations of binary search and their underlying principles.

Closed interval vs Left closed right open interval

p.s. the code can be verified through LeetCode.

There are mainly two kinds of styles to implement binary search. Closed interval, i.e. [ l e , r i ] [le, ri] [le,ri] and left closed right open interval, i.e. [ l e , r i ) [le, ri) [le,ri).

For closed interval, a classic Python code of binary search is

def search(self, nums, target):
    le = 0
    ri = len(nums)-1
    mid = 0
    while le <= ri:
        mid = (le+ri)//2
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            le = mid+1
        else:
            ri = mid-1
    return -1

There are 3 possible cases regarding the relationship between middle value and target. If the middle value is equal to the target, we’ve found the target and it’s time to break the loop. If the middle value is less than target, the target must be in the right half of current interval. Since the interval is closed and the middle value should not be included in the interval, we set the le to mid+1 to exclude middle value and just keep the right part. If the middle value is larger than target, the process is symmetric to less than and we will set ri to mid-1.

How about left closed right open version? Technically, this version just replaces the value of ri with ri+1. We can do some modification according to the new value.
For ri = len(nums)-1, it should be rewritten to ri = len(nums). (obvious)
For le <= ri, it should be rewritten to le < ri. (obvious)
For ri = mid-1, it should be rewritten to ri = mid, because now right value itself is also excluded by the interval.

Now, the left closed right open interval binary search works properly.

def search(self, nums, target):
    le = 0
    ri = len(nums)
    mid = 0
    while le < ri:
        mid = (le+ri)//2
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            le = mid+1
        else:
            ri = mid
    return -1

Is there something missed? Yeah! We did not rewrite the sentence mid = (le+ri)//2 to mid = (le+ri-1)//2 (though the results of binary search will also definitely works, you can try it on LeetCode). That’s because both (le+ri)//2 and (le+ri-1)//2 are located in the middle of interval [ l e , r i ) [le, ri) [le,ri) (approximately). When le+ri is odd, they are the same; when le+ri is even, (le+ri)//2 = (le+ri-1)//2 + 1. For example, when le=2, ri=4, (le+ri)//2=3 and (le+ri-1)//2=2. They all fall into the interval [ l e , r i ) [le, ri) [le,ri).

Floor vs Ceiling

After discussing the replacement of ri and ri+1, here comes another question. When we are computing mid, both of above compute it by mid=(le+ri)//2, which means we floor the result. Can we apply ceiling to the computation? Of course! The code below also works:

class Solution(object):
    def search(self, nums, target):
        le = 0
        ri = len(nums)-1
        mid = 0
        while le <= ri:
            mid = (le+ri+1)//2
            if nums[mid] == target:
                return mid
            if nums[mid] < target:
                le = mid+1
            else:
                ri = mid-1
        return -1

Whether mid is floored or ceiled, it still falls into the interval [ l e , r i ] [le, ri] [le,ri]. However, for interval [ l e , r i ) [le, ri) [le,ri), ceiling is not appliable, because r i ri ri is not in the interval.

The key principle is: mid have to fall into the location, and the endpoints of the interval shall move the exclude the last mid.

Therefore, comparing closed interval and left closed right open interval binary search, we can take left closed right open interval binary search as the ceiling version of closed interval one.

So, in the blog below, we will only discuss binary search in closed interval.

Lower Bound & Upper Bound

All the codes above are only able to search the position of an exact value, but what if we want to find first number that greater or equal to x (lower bound) or first number that greater than x (upper bound)?

Take lower bound as an example. To figure it out, let’s think step by step.

  1. If nums[mid] < target, then numbers less or equal to nums[mid], or say prior to mid, will be discarded, so we set le = mid+1.
  2. If nums[mid] >= target, then the numbers greater or equal to nums[mid], or say after mid (and mid itself) will be discarded, so we set ri = mid-1 and save current mid as a potential answer.
def lower_bound(nums, target):
    le = 0
    ri = len(nums)-1
    pos = -1
    while le <= ri:
        mid = (le+ri)//2
        if nums[mid] < target:
            le = mid+1
        else:
            pos = mid
            ri = mid-1
    return pos

If we want to perform an upper bound, all we need to do is to modify the condition.

def upper_bound(nums, target):
    le = 0
    ri = len(nums)-1
    pos = -1
    while le <= ri:
        mid = (le+ri)//2
        if nums[mid] <= target:
            le = mid+1
        else:
            pos = mid
            ri = mid-1
    return pos

General binary search

So, let’s look at all these binary searches and find a general structure!

def general_binary_search(nums, target):
	le = 0
	ri = len(nums)-1
	pos = -1
	while le <= ri:
		mid = (le+ri)//2
		if target seems appear in the right part of the interval (or just mid):
			(pos = mid)
			le = mid+1
		else: (target seems appear in the left part of the interval or just mid)
			(pos = mid)
			ri = mid-1

The condition describes the monotony of the sequence, depending on the specific property of the sequence.

Where we record the answer describes our behavior when there are multiple valid values. Record when moving left endpoint means search the right part, trying to find a valid value with greatest index; and record when moving right endpoint means search the left part, trying to find a valid value with least index.

Now, guess what the function of the code below is:

def bs3(nums, target):
    le = 0
    ri = len(nums)-1
    pos = -1
    while le <= ri:
        mid = (le+ri)//2
        if nums[mid] <= target:
            pos = mid
            le = mid+1
        else:
            ri = mid-1
    return pos

Because we record the answer under the condition nums[mid[ <= target and move left endpoint afterwards, the function is get number less or equal to target with greatest index.

What about change nums[mid] <= target into nums[mid] < target? We will get the number less or than target with greatest index.

def bs4(nums, target):
    le = 0
    ri = len(nums)-1
    pos = -1
    while le <= ri:
        mid = (le+ri)//2
        if nums[mid] < target:
            pos = mid
            le = mid+1
        else:
            ri = mid-1
    return pos

END

视觉特征-自监督-掩码特征预测【2024-11】:D-JEPA·T2I(通过下一词元预测实现高分辨率图像合成)【相对于D-JEPA的优化:文本条件、流匹配损失、VoPE】 近年来,自回归模型在类别条件图像生成方面展现了卓越的性能。然而,将下一词元预测应用于高分辨率文本到图像生成仍未得到充分探索。在本文中,我们提出了基于连续词元的自回归模型D-JEPA·T2I,该模型在架构和训练策略上均进行了创新,能够在高达4K的任意分辨率下生成高质量、照片级真实感的图像。在架构方面,我们采用去噪联合嵌入预测架构(D-JEPA),同时利用多模态视觉Transformer有效融合文本和视觉特征。此外,我们引入流匹配损失以及所提出的视觉旋转位置编码(VoPE),以实现连续分辨率学习。 阅读详情

相关推荐

聊一聊固态电池和钠离子电池新技术

总之,固态电池是一种“安全又高效的未来电池”,它的好处非常明显,但目前还处于研发阶段,离普及还有一段距离。未来,这两种技术可能会与锂离子电池并存,分别满足不同的市场需求。我尝试用最通俗易懂的语言将复杂的技术讲给大家听。钠离子电池和锂离子电池的工作原理很相似,但它用的是。固态电池和钠离子电池是两种正在研发和推广的。,它们有潜力解决现有锂离子电池的部分缺点。,而不是锂(Li)。

weixin_33324696的博客 3333

MuleSoft+LLM企业级AI编排:构建可审计、可治理的智能服务总线

企业AI落地的核心瓶颈并非模型能力,而是如何将大语言模型(LLM)深度嵌入现有IT资产——ERP、CRM、HRIS等异构系统中,实现语义化、可追溯、强治理的服务协同。这本质是AI编排(AI Orchestration)问题,需依托企业服务总线(ESB)级基础设施,完成结构化数据与自然语言意图的双向翻译、跨系统上下文编织、全链路可观测性保障及合规安全管控。MuleSoft凭借Anypoint Platform的API治理、DataWeave语义转换、Runtime Fabric混合云调度与开箱即用的可靠性机制

z466459262的专栏 405

Windows: 深入剖析pip install SSLError与SSL模块缺失的根源及系统级修复

本文深入分析Windows系统下pip install SSLError与SSL模块缺失的根本原因,提供系统级修复方案。从Python安装包缺失SSL支持、OpenSSL库冲突到环境变量配置问题,详细讲解四大成因及对应的解决方案,包括重新安装Python、手动修复OpenSSL依赖等实用技巧,帮助开发者彻底解决HTTPS连接问题。

weixin_28595749的博客 459

CodeCompass度量指标实战:用Tree Map直观展示圈复杂度、耦合度与内聚性

CodeCompass 是一款面向 C/C++、C# 和 Python 的开源代码理解工具(code comprehension tool),它的 Metrics 度量模块能把圈复杂度(McCabe)、耦合度(Ca/Ce)与内聚性(LcoH)等指标以 Tree Map 矩形树图的形式直观呈现,帮你一眼定位"该重构哪里"。这篇文章带你零基础完成第一次度量分析,并学会解读每一块矩形背后的含义。📊

gitblog_00061的博客 259

VCU128开发板上手记:搞定100G以太网IP核与QSFP光模块的那些坑

本文详细介绍了在VCU128开发板上实现100G以太网IP核与QSFP光模块调试的实战经验。从硬件准备、IP核配置到QSFP模块控制信号处理,文章揭示了数据手册中未提及的关键细节,并提供了优化参数和压力测试方案,帮助开发者快速解决UltraScale+平台下的高速以太网部署难题。

weixin_30740295的博客 521

【Ambari-Metrics监控】Grafana+Infinity快速构建DEMO-实战教学

摘要:本文介绍了如何通过Infinity插件在Grafana中监控Ambari-Metrics(AMS)的CPU核数指标。内容包括配置AMS REST API数据源、创建Dashboard面板、设置JSON解析规则,将时间戳和数值映射为时序数据。最终实现单个节点CPU核数曲线的可视化展示,该方法可扩展至其他AMS指标监控。文章提供了完整的配置示例和API调用验证方法,适用于Grafana 9.x及以上版本对接Ambari集群监控场景。

TTBIGDATA的博客 1352

Exercism Elixir 入门必读:44 个概念练习 + 134 个实践练习的完整学习地图

想学 Elixir 却不知道从哪里下手?这份 **Exercism Elixir 学习地图** 就是为你准备的。本文介绍的 elixi/elixir 项目是 Exercism 官方 Elixir 练习题库的完整镜像,包含 **44 个概念练习(Concept Exercise)** 和 **134 个实践练习(Practice Exercise)**,共 178 道题,覆盖从 Hello Worl

gitblog_00620的博客 437

攻防世界 misc题GFSJ1129-【您看我还有机会吗?】

我们发现了隐藏内容,一开始我以为那个英文就是flag,提交后发现不对,然后我想只有一张图片然后图片上的隐写内容又不是flag,那必定还有什么文件被隐藏了,于是我们打开VMware并启动Ubuntu,使用binwalk分析一下有没有隐藏文件,我们要在Terminal中分析,如下。我们发现里面有一个flag.txt文件,我们尝试提取里面内容,但发现又要密码,我们想起了之前图片上的隐藏内容,我们将那段英文输入(包括空格和符号,在VMware中输入密码不会有显示,你看到的就像没输入一样),然后我们看到如下。

大数据专业,关注 AI 安全与数学建模。记录 Web 安全、对抗攻击、隐私保护等安全实践,以及从经典模型到智能方法的建模思考。用数学思维理解 AI,用 AI 方法反哺安全与建模。 1099

Python 性能优化完全指南 2026 版:从 profiling 到 Cython 的全链路加速实战

本文是Python性能优化的实战指南,介绍了从性能测量到优化的全流程方法。主要内容包括:1) 性能优化的正确心态和闭环流程;2) 五大优化层级及其效果对比;3) 四种核心性能测量工具:timeit(微基准测试)、cProfile(函数级分析)、line_profiler(逐行分析)和memory_profiler(内存分析)。文章通过丰富代码示例展示了如何识别性能瓶颈,为后续优化打下基础,强调优化前必须先测量定位问题。

热爱技术与前沿创新,深耕科技领域,在科创中精进自我;探索技术乐趣,分享技术干货与成长心得,以技术为伴,热爱生活,在科创与生活中双向成长。 279

1分钟了解LangChain是什么?

是一个基于大型语言模型(LLM)开发应用程序的框架, 它旨在简化语言模型应用的开发流程,特别是在构建对话系统和其他基于语言的AI解决方案时.目标是将复杂的语言模型技术转化为可通过简单API调用实现的功能,从而使开发者能够更加专注于创造性的解决方案设计。高效地解决了开发大语言模型应用的痛点问题。Langchain 最主要的特色是可以将 LLM 应用研发过程中的交互 Prompt、LLM 模型调用、语言模型与环境互动的自适应等方式融为一体。

gorgor在码农 2631

Python + Playwright:集成 Applitools 进行视觉回归测试(快速入门)

Applitools是一款基于人工智能的视觉验证测试工具,专门用于自动化和验证应用程序的用户界面(UI);Applitools使用视觉回归测试来检测应用程序界面的变化,确保 UI 在不同版本之间的一致性;Applitools的核心功能是通过视觉比较,检测 UI 元素的差异,而无需手动编写复杂的界面检查代码;通过集成Applitools,测试人员可以轻松捕捉和验证界面中的视觉差异,无论是在Web移动端或桌面应用的测试环境;

blues_C的博客 2922

Python数据结构实战:从问题诊断到性能决策

数据结构是程序性能的底层基石,其本质是根据读写比例、数据规模和操作类型,在时间与空间代价间做出工程权衡。理解列表、字典、堆、双端队列等内置结构的原理与适用边界,远比手写算法更重要;而`heapq`、`collections.deque`、`array.array`等标准库组件,正是CPython针对真实场景深度优化的技术结晶。它们支撑着电商库存扣减、日志高频统计、实时推荐向量、消息优先级调度等典型应用。本文聚焦Python工程实践中的结构选型逻辑,融合Data-structures and Algorith

348

【批处理脚本】-0.1-如何运行批处理bat文件

如何运行批处理bat文件

「汽车电子助手」的博客 1586

BERT:基于 Transformer 的深层双向编码器表示预训练方法,用于语言理解

本文提出 BERT,一种基于深度双向 Transformer 的语言表示模型。BERT通过掩码语言模型(MLM)和下一句预测(NSP)进行大规模预训练,学习双向上下文语义表示,并通过微调适配多种自然语言处理任务。实验表明,BERT在文本分类、问答、自然语言推断等任务中取得显著提升,验证了深度双向预训练模型的有效性。

lihao2372的专栏 203

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

Claude Code高阶用法:10个提升AI编程效率的实用技巧

在AI辅助编程领域,精准的指令交互是提升开发效率的核心。其原理在于通过结构化的输入,引导大语言模型进入特定领域语境,从而生成更准确、更符合预期的代码。这种交互方式的技术价值在于,它能将开发者从繁琐的语法细节和重复性调试中解放出来,专注于算法设计和架构思考。在实际应用场景中,无论是全栈开发、脚本编写还是系统运维,掌握高效的AI协作模式都能显著缩短开发周期。本文聚焦于Claude的`/code`命令,深入解析其超越基础代码块标记的高阶用法。通过结合**代码调试**与**单元测试**等热词,文章系统介绍了如何利用

weixin_30617737的博客 317

jre9下载 jdk9

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

LangGraph多模态Agent实战:图像+文本+知识库协同推理

多模态AI是指让模型同时理解图像、文本、结构化数据等多种信息形式的技术范式。其核心原理在于跨模态对齐与协同推理,而非简单拼接单模态能力。技术价值体现在提升工业质检、图纸审核、医疗报告分析等场景的准确率与可解释性。典型应用场景包括电路板缺陷识别、机械图纸公差合规检查、设备故障代码匹配手册等,需融合OCR、视觉检测、向量检索与大语言模型。本文聚焦LangGraph图工作流设计,详解如何通过状态管理、条件边控制与分层工具封装,构建高鲁棒、低成本、可监控的生产级多模态Agent。

chuanggangbo5551的博客 462

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

BERT:用于语言理解的深度双向 Transformer 预训练

Abstract摘要我们提出了一种新的语言表示模型,称为 BERT,即来自Transformer的双向编码器表示。与近期的语言表示模型(Peters et al., 2018a;Radford et al., 2018)不同,BERT 旨在通过在所有层中联合利用左右上下文,从无标注文本中预训练深度双向表示。因此,只需添加一个额外的输出层,即可对预训练的BERT模型进行微调,从而为包括问答和语言Inference在内的广泛任务创建最先进的模型,而无需对特定任务的架构进行实质性修改。

u013250861的博客 127

python3 核心笔记

本文主要是针对python3的一些核心要点做一些记录,感兴趣的可以关注和订阅。会持续更新,这个玩意学习一下,可以为数据分析和AI打下一定的基础。

yanghuashuiyue的专栏 621

书店管理系统(C++初学者友好版)

文章目录写在前面题目要求主体思路代码实现定义结构体book读入带空格字符串的函数通过书名查找书的编号进货函数出货函数查询某书的详细信息、销售情况、库存函数查询详细信息函数查询销售情况函数查询库存函数查询进/出货记录函数排序函数其他函数输出带空格字符串函数输出一本书的详细信息函数输出操作列表函数完整代码结语 写在前面 正如标题所示,本文是写给C++的初学者的一个书店管理系统实例。为了贴近目标读者的需求,本篇博客中的代码仅采用了初级的内容。比如:对于书的名字,采取了最简单粗暴的多维字符串存储而不是Trie树甚或

ShadyPi的IT笔记 2968

[2018.11.03 T4] 7w523

7w523 题目描述 你玩过7王523吗? 这个扑克牌游戏可以 2~5 个人玩,最开始的时候,每人 555 张牌,庄家 666 张牌。庄家首先出牌,然后轮流出牌或不出牌。 第一个出牌的人可以打出任意牌,后面的人必须比前面的牌大才能出牌,且牌型必须要和前面人出牌的牌型一致或大于前面人的牌型。 牌的大小关系是 7&gt;大王&gt;小王&gt;5&gt;2&gt;3&gt;A&gt;K&gt;Q&gt...

ShadyPi的IT笔记 2238

[NeetCode 150] Word Ladder

【代码】[NeetCode 150] Word Ladder。

ShadyPi的IT笔记 1234

[NeetCode 150] Serialize and Deserialize Binary Tree

Tree traversal

ShadyPi的IT笔记 1205

[NeetCode 150] Eating Bananas

Binary search the answer

ShadyPi的IT笔记 976

[NeetCode 150] Rotate Matrix

【代码】[NeetCode 150] Rotate Matrix。

ShadyPi的IT笔记 970

[LeetCode] 75. Sort Colors

Quick Sort

ShadyPi的IT笔记 911
上一篇: [NeetCode 150] Search 2D Matrix
下一篇: [NeetCode 150] Find Target in Rotated Sorted Array
ShadyPi
博客等级 码龄9年 1万+粉丝 637原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

打赏作者

ShadyPi

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

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

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

打赏作者

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

抵扣说明:

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

余额充值