1.利用哈希表
class Solution {
public:
bool isAnagram(string s, string t) {
unordered_map<char, int> map;
for (int i = 0; i < s.length(); i++) {
if (map.count(s[i])) {
map.at(s[i])++;
} else {
map.insert(pair<char, int>(s[i], 1));
}
}
for (int i = 0; i <t.length(); i++) {
if (map.count(t[i])) {
map.at(t[i])--;
}else {
return false;
}
}
for(auto it : map) {
if (it.second != 0) {
return false;
}
}
return true;
}
};
2.利用数组作为hash表
class Solution {
public:
int arr[26];
bool isAnagram(string s, string t) {
if (s.length() != t.length()) {
return false;
}
for (int i : s) {
i = i - 'a';
arr[i] += 1;
}
for (int j : t) {
j = j - 'a';
arr[j] -= 1;
}
for (int k : arr) {
if (k != 0 ) {
return false;
}
}
return true;
}
};
1.利用hashset
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> res;
unordered_set<int> set(nums1.begin(), nums1.end());
for (int it : nums2) {
if (set.count(it)) {
res.push_back(it);
set.erase(it);
}
}
return res;
}
};
2.利用数组作为hash表
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> res;
int arr[1001] = {0};
for(int i : nums1) {
arr[i] = 1;
}
for (int j : nums2) {
if (arr[j]) {
res.push_back(j);
arr[j] = 0;
}
}
return res;
}
};
题目提到可能是无限循环,就知道了如果在hash表中存在过当前的数值,那么就可以return false;
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> set;
int sum = getSum(n);
while (!set.count(sum)) {
set.insert(sum);
if (sum == 1) {
return true;
}
sum = getSum(sum);
}
return false;
}
int getSum(int n ) {
int sum = 0;
while (n) {
sum += pow(n % 10, 2);
n /= 10;
}
return sum;
}
};
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> hashmap;
hashmap.insert(make_pair(nums[0], 0));
for (int i = 1; i < nums.size(); i++)
{
if (hashmap.count(target - nums[i]))
return {i, hashmap[target - nums[i]]};
hashmap.insert(make_pair(nums[i], i));
}
return {0};
}
};