242.有效的字母异位词
思路:判断两个字符串是否是字母异位词,需要对字符串中每种字符的数目进行统计。可以考虑unordered_map,但是本题中限定了所有字符均为小写字母,使用数组即可。
题解:
class Solution {
public:
bool isAnagram(string s, string t) {
int hash[26] = {0};
for (char ch : s)
hash[ch - 'a'] += 1;
for (char ch : t)
hash[ch - 'a'] -= 1;
for (int n : hash)
{
if (n != 0)
return false;
}
return true;
}
};
349. 两个数组的交集
思路:对其中一个数组进行统计,遍历另一个数组即可。感觉主要考察的是STL,多熟悉vector、set、map的各种操作以及迭代器相关的内容。
题解:
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> nums;
unordered_set<int> ret;
for (int num : nums1)
{
if (nums.find(num) == nums.end())
nums.insert(num);
}
for (int num : nums2)
{
if (nums.find(num) != nums.end())
ret.insert(num);
}
return vector<int>{ret.begin(), ret.end()};
}
};
202. 快乐数
思路:先写个求每个位置数字平方和的函数,方便后续处理。把实参每次计算后的结果存起来,如过后面发现计算后的结果在之前出现过,则说明陷入循环,不是快乐数。因为要快速查询某个集合中是否出现过某个元素,考虑用哈希表,因为只需要存数字,用unordered_set。
题解:
class Solution {
public:
int caculate_sum (int n)
{
int sum{0};
while (n)
{
sum += (n % 10) * (n % 10);
n /= 10;
}
return sum;
}
bool isHappy(int n) {
unordered_set<int> hash;
int sum{n};
while (1)
{
if (sum == 1)
return true;
sum = caculate_sum(sum);
if (hash.find(sum) != hash.end())
return false;
else
hash.insert(sum);
}
}
};
1. 两数之和
思路:因为要返回下标,所以使用unordered_map存储数字和其对应下标。每遍历一个数字,就查询一下map有没有对应的可以凑成target的数字,没有就把这个数字加入map。需要熟悉STL。
题解:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hash;
for (int i = 0; i < nums.size(); ++i)
{
auto it = hash.find(target - nums[i]);
if(it == hash.end())
hash[nums[i]] = i;
else
return vector<int>{it->second, i};
}
return vector<int>{0};
}
};