慣性聚合 高效追讀感興趣之博客、新聞、科技資訊
閱原文 以慣性聚合開啟

推薦訂閱源

博客园 - 司徒正美
V
V2EX
T
Tailwind CSS Blog
有赞技术团队
有赞技术团队
aimingoo的专栏
aimingoo的专栏
Apple Machine Learning Research
Apple Machine Learning Research
IT之家
IT之家
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
月光博客
月光博客
T
The Blog of Author Tim Ferriss
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
The GitHub Blog
The GitHub Blog
V
Visual Studio Blog
WordPress大学
WordPress大学
酷 壳 – CoolShell
酷 壳 – CoolShell
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python)
力扣解法:一、两数之和
Kushal Jain · 2026-05-24 · via DEV Community

尔初涉力扣之旅:从容克“两数之和”(题一)!

诸君同仁,吾乃Kushalx,今朝共探算法之基石:力扣之首题,即“两数之和”也。尔方初涉LeetCode之境,此乃入径之佳所。此题甚妙,引汝于反复用之之要义。

今且析之,明其解之所以然,俾尔备将来之挑战!


一、题意阐释

尔若有数列,复有特定之"目标"数。尔之任,若尔愿承之,乃于数列中觅得二数,使二者之和等于目标。既得之,须返其于原列之位次(索引)。

兹为详述:

尔所予者:

  • 整数之列nums.
  • 整数target.

汝需:

  • 返其两数之序,使之和为target.

要旨:

  • 可假定之每输入必有一解莫忧多对或无解之虞!
  • 不可复用一物倘若有之nums[0]若为总数之一部,则不可用也。nums[0]复为第二数。
  • 君可依序返答(如,)[0, 1][1, 0]甚善。

吾等观数例,以明其理。

例一:
nums = [2, 7, 11, 15]target = 9

  • 于此nums[0](是也)2) +nums[1](是也)7) 等于9请提供需要翻译的英文文本。
  • 故,其输出应为[0, 1].

例二:
nums = [3, 2, 4]target = 6

  • nums[1](是也)2) +nums[2](是也)4) 等于6.
  • 輸出:[1, 2].

例三:
nums = [3, 3]target = 6

  • nums[0](是也)3) +nums[1](是也)3) 等于6
  • 輸出:[0, 1]吾等须知,虽其值同,然所用工具,实有二种。

所当谨记之约束也

  • 此列nums 至少含二数,至多不逾一万.
  • 列中numstarget 之数,或大或小(介于负十亿至十亿之间).

2. 直觉

面此难题,人常首念径直之法: "悉察诸可能之对!"

蛮力之术(及其非宜之由)

若欲检视每一对,可如此为之:

  1. 取首数nums[0])。
  2. 加之诸数之偶nums[1]nums[2],……)。
  3. 若有数等之target,事毕矣!
  4. 若不然,取其次数nums[1]) 并加之于每数而后nums[2]nums[3],……)。
  5. 续此法,直至得一对。

此法可行!必得答案矣。
然则,试思一列含万数者。

  • 首数之验,或可及九千九百九十九余数。
  • 其次,至九千九百九十八。
  • 如此类推...

此迅速积聚至林。于操作之事。若以计算机之语论之,此乃O(n平方)解(读作“O of n squared”),其n乃元素之数。n = 10,000n^2100,000,000(一亿)!虽计算机速,然此对大输入或缓。所谓“后续”明求其事。不逾O(n^2).

智识之思:吾等何为诚然何寻?

吾辈当复思之。若吾等有currentNumber吾知之矣。target,何谓之他者数之所在乎?
此诚然也target - currentNumber吾等可称之为此。complement请提供需要翻译的英文文本。

故,于每currentNumber吾等之列,须速答其问:其有乎?complement现矣在列之前,若在,其索引为何?"

若能极速解答此问,则胜矣!


3. 方略

此乃玄妙数据结构登场之处:哈希映射(Python中称Dictionary,Java中称HashMap等)。

哈希映射使汝得存key-value 並,要緊者,於 average O(1) 時間內,以 恒定時間!此速至極,猶翻開字典直指所求之字。

此乃精進之策,用散列之圖:

  1. 設一空散列之圖: 此圖將存吾人所見之數,爲 鍵。與其indices作為values。(例如,{number: index}。)
  2. 遍歷nums數組:吾將逐一審視每數,並記其序。
  3. currentNumber之序index i a.complement complement = target - currentNumber。 b. complement是否已入吾之Hash Map: * 若numMap.containsKey(complement)true: * 得之矣!吾等已得所求之对!complement尝见之,其序为numMap.get(complement)currentNumber在焉index i[numMap.get(complement), i]若其complement不可。在哈希映射中: * 此currentNumber岂非其次吾等已睹此对之一部,故加之。currentNumber其自附于吾图,并其索引,俾其或为后见之数之一偶。numMap.put(currentNumber, i)请提供需要翻译的英文文本。

既知其题必有一解,则必得一对而早出其环。无复忧其环终而未返也。


四. 代码

吾辈当以Java之码,践行此道。

import java.util.HashMap;
import java.util.Map;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // Create a HashMap to store numbers and their indices.
        // Key: The number itself
        // Value: The index of that number in the 'nums' array
        Map<Integer, Integer> numMap = new HashMap<>();

        // Iterate through the array 'nums' using an index 'i'
        for (int i = 0; i < nums.length; i++) {
            int currentNum = nums[i]; // Get the current number

            // Calculate the 'complement' needed to reach the target
            // If currentNum + complement = target, then complement = target - currentNum
            int complement = target - currentNum;

            // Check if the 'complement' already exists as a key in our map.
            // If it does, it means we've seen this 'complement' before,
            // and its index is stored as the value associated with the 'complement' key.
            if (numMap.containsKey(complement)) {
                // We found our pair!
                // The index of the complement is numMap.get(complement)
                // The index of the current number is 'i'
                return new int[] { numMap.get(complement), i };
            }

            // If the complement is NOT found in the map, it means the currentNum
            // hasn't found its partner yet. So, we add currentNum to the map
            // along with its index. This way, if a future number's complement
            // is this currentNum, we'll find it.
            numMap.put(currentNum, i);
        }

        // According to the problem constraints, there will always be exactly one solution.
        // Therefore, this line should theoretically never be reached.
        // It's good practice to have a default return, or throw an exception
        // if the problem didn't guarantee a solution.
        return new int[0]; 
    }
}

入全景模式 出全景模式


五. 时空复杂度析 与

明己码之效,乃竞技编程与软件工程之要术也.

时复杂度:O(n)

  • 吾遍历nums之数列,仅一次耳。
  • 循环之内,numMap.containsKey()numMap.get()numMap.put() 诸务,皆需 之平均 O(1) (常数) 之时。至若最劣之境(典型哈希映射之实,此境鲜见),此诸务或可降为 O(n),然于实用与竞技编程,吾等视之平均为 O(1)。
  • 每一n元素,吾辈皆施以常数项之O(1)操作,故总时复杂度乃O(n)。此较之O(n^2)之蛮力法,实乃大进!

空间复杂度:O(n)

  • 最劣之境,吾辈或需遍历几近全体nums于配对之前寻数组(如,末二者为所求)。
  • 若斯,则其numMap可蓄至n-1元素。
  • 故散列表所需之空间,随输入之量而线性增。n.
  • 故而,其空间复杂度也O(n).

6. 要领

  • 哈希表乃速查之良伴! 每欲速察元素有否或索其关联之数据,当思哈希表(或称字典)。此法化 O(n) 或 O(n^2) 之搜查难题为平均 O(1)。
  • "补数"之策: 涉及和差之题,多可化繁为简,思其所补。他者数至目标之数。complement = target - currentNumber乃强有力之范式也。
  • 时与空之权衡吾等以额外之空间(O(n))构建哈希表,遂得时间复杂度更优(O(n))。此乃算法中常见之权衡。时则优化空间,时则优化时序,皆因约束而异。
  • 勿以繁术始。始以蛮力之思,识其局限,继而思数据结构何以助其优化。

七、投递之细

  • 作者之帐:库沙尔克斯(Kushalx)
  • 刊刻之时二零二六年五月廿四日未时初十一分十一秒
  • 难题: 1. 两个数之和

此题乃登堂之阶。熟之,则诸多力扣之题,皆可迎刃而解!勤码,勤学,乐解之!✨