前言
这是关于哈希表的相关练习
基础知识
习题
第一想法直接用了暴力循环
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)
{
count += hash[nums[i]];
++hash[nums[i]];
}
return count;
}
};
class Solution {
public:
int countKDifference(vector<int>& nums, int k) {
int hash[101] = {0};
int count = 0;
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;
}
};
|