算法效率的评价指标可分为时间复杂度和空间复杂度
// 空间复杂度O(N),若N为常数即为O(1)
for (size_t i = 0; i < N; i++)
// 空间复杂度O(N*M),若第二个循环为N即为O(N^2)
for (size_t i = 0; i < N; i++)
for (size_t i = 0; i < M; i++)
;
Note:随着存储容量的增大,空间复杂度的消耗变得不再重要。通常优先可空间换时间的方式算法改进。
定义
unordered_map<key, value> hash_Map;
// key, value : int / string / char;
常见的哈希表操作
增
//.insert()函数
hash_Map.insert(pair<int,int>(key, value));
// 数组
hash_Map[key] = value;
删
// .erase()函数
hash_Map.erase(key);
改
// 数组, 改变键对应的值
hash_Map[key] = new_value;
// .replace()函数
hash_Map.replace(old_key now_key, old_value new_value);
查
// .find()函数, 存在返回键对应的值,不存在返回迭代器hash_Map.end()
hash_Map.find(key);
// .count()函数,返回1/0;底层由find()函数实现
hash_Map.count(key);
1.暴力枚举 – O ( N 2 ) , O ( 1 ) O(N^{2}), O(1) O(N2),O(1)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i,j;
for(i = 0; i < nums.size(); i++)
{
for (j = i + 1; j < nums.size(); j++)
{
if (nums[i] + nums[j] == target)
{
return {i,j};
}
}
}
return {};
}
};
2.哈希表 – O ( N ) , O ( N ) O(N), O(N) O(N),O(N)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hash_Map;
for(int i = 0; i < nums.size(); i++)
{
int temp = target - nums[i];
//if(hash_Map.count(temp)) // count()的底层依靠find()实现, 相对而言会更慢.
if(hash_Map.find(temp) != hash_Map.end()) //
{
return {hash_Map[temp], i};
}
hash_Map[nums[i]] = i;
}
return {};
}
};
因篇幅问题不能全部显示,请点此查看更多更全内容