day5打卡

ikun1111發表於2024-08-19

有效的字母異位詞
class Solution {
public:
bool isAnagram(string s, string t) {
int record[26] = {0};
for(int i = 0; i < s.size(); ++i)
{
record[s[i] - 'a']++;
}
for(int i = 0; i < t.size(); ++i)
{
record[t[i] - 'a']--;
}
for(int i = 0; i < 26; ++i)
{
if(record[i] != 0)
{
return false;
}
}
return true;
}
};

兩個陣列的交集

class Solution {
public:
vector intersection(vector& nums1, vector& nums2) {
unordered_set result;
unordered_set nums_set(nums1.begin(), nums1.end());
for(int num : nums2)
{
if(nums_set.find(num) != nums_set.end())
{
result.insert(num);
}
}
return vector(result.begin(), result.end());
}
};

快樂數

class Solution {
public:
vector intersection(vector& nums1, vector& nums2) {
unordered_set result;
unordered_set nums_set(nums1.begin(), nums1.end());
for(int num : nums2)
{
if(nums_set.find(num) != nums_set.end())
{
result.insert(num);
}
}
return vector(result.begin(), result.end());
}
};

兩數之和
class Solution {
public:
vector twoSum(vector& nums, int target) {
vector ret;
unordered_map<int, int> map;
for(int i = 0; i < nums.size(); ++i)
{
if(map.find(target - nums[i]) != map.end())
{
ret.push_back(map[target - nums[i]]);
ret.push_back(i);
}
else
{
map.insert(pair<int,int>(nums[i],i));
}
}
return ret;

}

};