給定整數數組 nums 和目標值 target,找出兩數下標使其和為 target。假設唯一解,下標從 1 開始。
遍歷數組,對每個 x 查找 target - x 是否已在表中。若存在直接返回;否則將 x 存入表。時間 O(n),空間 O(n)。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> pos; // 值 -> 索引(0-based)
for (int i = 0; i < nums.size(); ++i) {
int need = target - nums[i];
if (pos.count(need)) return {pos[need]+1, i+1};
pos[nums[i]] = i;
}
return {};
}
};
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
int need = target - nums[i];
if (map.containsKey(need)) return new int[]{map.get(need)+1, i+1};
map.put(nums[i], i);
}
return new int[0];
}
}
unordered_map 平均 O(1) 查找/插入。O(n) 平均。O(n)。