赞
踩
target - nums[i]
,就能快速的找到「⽬标和的下标」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 tmp = target - nums[i]; if(hash.count(tmp)) { return {hash[tmp], i}; } hash[nums[i]] = i; } return {-1, -1}; }
hash[x]++
hash[x]--
< 0
的,则不构成重排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; }
bool ContainsDuplicate(vector<int>& nums) { unordered_set<int> hash; // <nums[i]> for(auto& x : nums) { if(hash.count(x)) { return true; } else { hash.insert(x); } } return false; }
bool ContainsNearbyDuplicate(vector<int>& nums, int k)
{
unordered_map<int, int> hash; // <nums[i], i>
for(int i = 0; i < nums.size(); i++)
{
if(hash.count(nums[i]) && i - hash[nums[i]] <= k)
{
return true;
}
hash[nums[i]] = i;
}
return false;
}
hash<string, vector<string>>
string
当做哈希表的key
值string[]
)当成val
值vector<vector<string>> GroupAnagrams(vector<string>& strs) { unordered_map<string, vector<string>> hash; for(auto& str : strs) { string tmp = str; sort(tmp.begin(), tmp.end()); hash[tmp].push_back(str); } vector<vector<string>> ret; for(auto& [x, y] : hash) // 这种写法积累下来 { ret.push_back(y); } return ret; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。