Leetcode热题100 --1.两数之和
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashtable;
for (int i = 0; i < nums.size(); ++i) {
auto it = hashtable.find(target - nums[i]);
if (it != hashtable.end()) {
return {it->second, i};
}
hashtable[nums[i]] = i;
}
return {};
}
};
本文提供了一种高效解决LeetCode经典题目“两数之和”的方法。通过使用哈希表来存储已遍历过的数值及其索引,能够在遍历过程中快速查找目标值对应的配对元素,实现O(n)的时间复杂度。
8万+

被折叠的 条评论
为什么被折叠?



