Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
分类: technical
难度: easy
标签:
答题技巧
["Optimal solution uses hash map (one-pass hash)","Time O(n), Space O(n)","Brute force O(n²) is acceptable for junior roles","Must clarify: cannot use same element twice","Follow-up possible: multiple solutions? duplicates in array?","Return indices, not values"]
参考答案
Hash map solution: ```javascript function twoSum(nums, target) { const map = new Map(); for (let i = 0; i < nums.length; i++) { const complement = target - nums[i]; if (map.has(complement)) { return [map.get(complement), i]; } map.set(nums[i], i); } return []; } ```