尔初涉力扣之旅:从容克“两数之和”(题一)!
诸君同仁,吾乃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至少含二数,至多不逾一万. - 列中
nums与target之数,或大或小(介于负十亿至十亿之间).
2. 直觉
面此难题,人常首念径直之法: "悉察诸可能之对!"
蛮力之术(及其非宜之由)
若欲检视每一对,可如此为之:
- 取首数
nums[0])。 - 加之诸数之偶
nums[1],nums[2],……)。 - 若有数等之
target,事毕矣! - 若不然,取其次数
nums[1]) 并加之于每数而后它nums[2],nums[3],……)。 - 续此法,直至得一对。
此法可行!必得答案矣。
然则,试思一列含万数者。
- 首数之验,或可及九千九百九十九余数。
- 其次,至九千九百九十八。
- 如此类推...
此迅速积聚至林。于操作之事。若以计算机之语论之,此乃O(n平方)解(读作“O of n squared”),其n乃元素之数。n = 10,000,n^2是100,000,000(一亿)!虽计算机速,然此对大输入或缓。所谓“后续”明求其事。不逾O(n^2).
智识之思:吾等何为诚然何寻?
吾辈当复思之。若吾等有currentNumber吾知之矣。target,何谓之他者数之所在乎?
此诚然也target - currentNumber吾等可称之为此。complement请提供需要翻译的英文文本。
故,于每currentNumber吾等之列,须速答其问:其有乎?complement现矣在列之前,若在,其索引为何?"
若能极速解答此问,则胜矣!
3. 方略
此乃玄妙数据结构登场之处:哈希映射(Python中称Dictionary,Java中称HashMap等)。
哈希映射使汝得存key-value 並,要緊者,於 average O(1) 時間內,以 恒定時間!此速至極,猶翻開字典直指所求之字。
此乃精進之策,用散列之圖:
- 設一空散列之圖: 此圖將存吾人所見之數,爲 鍵。與其indices作為values。(例如,
{number: index}。) - 遍歷
nums數組:吾將逐一審視每數,並記其序。 - 於
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. 两个数之和
此题乃登堂之阶。熟之,则诸多力扣之题,皆可迎刃而解!勤码,勤学,乐解之!✨












