赞
踩
哈希表,其作用在于快速查找特定的值,从而优化时间复杂度,但会增加空间复杂度,典型以空间换时间。在做题的过程中,可以用数组模拟(数据范围小且数据为正),也可以用容器实现。
思路:
为什么之前的暴力策略不好用了呢?
因为按照之前的暴力策略,要事先将所有的数都存入哈希表中,再在哈希表中进行查找。同时,因为有可能查找到自身元素,所以还要额外判断排除这种情况。class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
unordered_map<int, int> hash;//<nums[i], i>
for(int i=0; i<nums.size(); i++)
{
int n = target - nums[i];
if(hash.count(n)) return {hash[n], i};
hash[nums[i]] = i;
}
return {};
}
};
思路:
class Solution { public: bool CheckPermutation(string s1, string s2) { if(s1.size() != s2.size()) return false;//优化 int hash[26] = { 0 }; for(auto ch : s1) hash[ch - 'a']++; for(auto ch : s2) { hash[ch - 'a']--; if(hash[ch - 'a'] < 0) return false;//优化 } return true; } };
思路:
class Solution
{
public:
bool containsDuplicate(vector<int>& nums)
{
unordered_set<int> hash;
for(auto x : nums)
{
if(hash.count(x)) return true;
hash.insert(x);
}
return false;
}
};
思路:
class Solution
{
public:
bool containsNearbyDuplicate(vector<int>& nums, int k)
{
unordered_map<int, int> hash;//<nums[i], i>
for(int i=0; i<nums.size(); i++)
{
int x = nums[i];
if(hash.count(x) && i - hash[x] <= k) return true;
hash[x] = i;
}
return false;
}
};
思路:
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string, vector<string>> hash; for(auto& str : strs) { string s = str; sort(s.begin(), s.end()); hash[s].push_back(str); } vector<vector<string>> ret; for(auto& kv : hash) ret.push_back(kv.second); return ret; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。