Leetcode 242 有效的字母异位词
题目链接: 有效的字母异位词
Solution:
- 哈希表
class Solution {
public:
bool isAnagram(string s, string t) {
int hash[26] = {0};
for(auto ch : s) {
hash[ch - 'a']++;
}
for(auto ch : t) {
hash[ch - 'a']--;
}
for(int i = 0; i < 26; i++) {
if(hash[i] != 0)
return false;
}
return true;
}
};
Leetcode 349 两个数组的交集
题目链接:两个数组的交集
Solution:
- 哈希法
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int>nums1_set(nums1.begin(), nums1.end());
unordered_set<int>res;
for(auto ch : nums2) {
if(nums1_set.find(ch) != nums1_set.end()) {
res.insert(ch);
}
}
return vector<int>(res.begin(), res.end());
}
};
Leetcode 202 快乐数
题目链接:快乐数
Solution:
- 哈希法
class Solution {
public:
int get_sum(int n) {
int sum = 0;
while(n) {
sum += (n%10)*(n%10);
n /= 10;
}
return sum;
}
bool isHappy(int n) {
unordered_set<int>set;
int sum = 0;
while(1) {
sum = get_sum(n);
if(sum == 1)
return true;
if(set.find(sum) != set.end()) {
return false;
} else {
set.insert(sum);
}
n = sum;
}
}
};
Leetcode 1 两数之和
题目链接:两数之和
Solution:
- 哈希法
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int>map;
for(int i = 0; i < nums.size(); i++) {
auto iter = map.find(target - nums[i]);
if(iter != map.end()) {
return {i, iter->second};
}
map[nums[i]] = i;
}
return {};
}
};