Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input has exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
这道题是经典的 Two Sum,核心思路是用哈希表在遍历数组时快速查找“目标值减去当前值”的补数,从而把时间复杂度从暴力枚举的 O(n^2) 降到 O(n)。做法很直接:依次扫描 nums,先检查 target – nums[i] 是否已经出现过;如果出现过,直接返回这两个下标;否则把当前数字及其位置记录到哈希表中。题目通常保证只有一组解,并且不能重复使用同一个元素,因此这种“一边遍历一边查找”的方式最适合面试和 OA 场景。