文章目录
前言
这是关于哈希表的相关练习
基础知识
习题
1512. 好数对的数目
第一想法直接用了暴力循环
class Solution {
public:
int numIdenticalPairs(vector<int>& nums) {
// 暴力双循环
int count = 0; // 计数
for(int i = 0; i < nums.size(); ++i)
{
for(int j = i + 1; j < nums.size(); ++j)
{
if(nums[i] == nums[j])
++count;
}
}
return count;
}
};
既然是哈希专项练习,当然得用哈希思想解决啦
class Solution {
public:
int numIdenticalPairs(vector<int>& nums) {
// 哈希+计数
int hash[101] = {0};
int count = 0; // 计数
for(int i = 0; i < nums.size(); ++i)
{
// 一开始哈希表里都是0,直接加上去就行
count += hash[nums[i]];
++hash[nums[i]];
}
// nums 1 2 3 1 1 3
// hash 0 3 1 2 0 0
// 是在++hash[nums[i]]统计的,因此统统-1
return count;
}
};
2006. 差的绝对值为 K 的数对数目
class Solution {
public:
int countKDifference(vector<int>& nums, int k) {
// |nums[i] - nums[j]| == k 即
// nums[i] - nums[j] == k 和 nums[j] - nums[i] == k
// 也就是 nums[i] == nums[j] + k; nums[j] == nums[i] + k
// 类比1512,容器里放的是0~i-1 的数字的计数,此题容器里应该放nums[j] + k,nums[i] + k的数字的计数
int hash[101] = {0};
int count = 0;
// 分别查找nums[i]+k,nums[i]-k 是否在哈希表里,并且累加计数
// 最好将nums[i]插入哈希表
for(int i = 0; i < nums.size(); ++i)
{
int x = nums[i] + k;
if(x >= 1 && x <= 100)
{
count += hash[x];
}
x = nums[i] - k;
if(x >= 1 && x <= 100)
{
count += hash[x];
}
++hash[nums[i]];
}
return count;
}
};