LeetCode1 Two Sum
Given an array of integers and an integer , return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
暴力搜索法
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); ++i) {
for (int j = i + 1; j < nums.size(); ++j) {
if (nums[i] + nums[j] == target) {
return {i, j};
}
}
}
return {};
}
};
时间复杂度:
初学cpp注释:
- 定义了
Solution类,类中有public类型的函数twoSum. vector<int>类似变长数组.vector的长度用.size()表示.- &表示对对象的引用,不会复制
nums,而是直接对nums进行操作.
哈希表
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashMap;
for (int i = 0; i < nums.size(); ++i) {
int complement = target - nums[i];
if (hashMap.count(complement)) {
return {hashMap[complement], i};
}
hashMap[nums[i]] = i;
}
return {};
}
};
时间复杂度:
初学cpp注释:
unordered_map是C++标准库提供的一个哈希表容器,用于以常数平均时间O(1)进行快速查找,插入和删除操作.功能类似于Python的字典(dict).
引入头文件:#include <unordered_map>
基本语法:unordered_map<KeyType, ValueType> myMap;,即unordered_map<键类型, 值类型> 名称
常用操作:
| 操作 | 示例代码 | 说明 |
|---|---|---|
| 插入元素 | map[key] = value; | 若 key 存在则更新,否则插入 |
| 查找元素 | map.count(key) 或 map.find(key) | 判断 key 是否存在 |
| 获取值 | int val = map[key]; | 获取 key 对应的值 |
| 遍历元素 | 使用范围 for 循环 | 遍历所有 key-value 对 |