242.有效的字母异位词
class Solution {
public:
bool isAnagram(string s, string t) {
int hash[26];
for(int i = 0; i < s.size(); i++){
hash[s[i]-'a']++;
}
for(int i = 0; i < t.size(); i++){
hash[t[i]-'a']--;
}
for(int i = 0; i < t.size(); i++){
if(hash[i]!=0)return false;
}
return true;
}
};
349. 两个数组的交集
set实现:
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> result_set;//用于存放结果,之所以用set是为了给结果去重
unordered_set<int> nums_set(num1.begin(), num2.end());
for(int num : num2){
if(nums_set.find(num) != nums_set.end()){
result_set.insert(num);
}
}
return vector<int>(result_set.begin(),result_set.end());
}
};
数组实现:
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> result_set;//用于存放结果,之所以用set是为了给结果去重
int hash[1005] = {0};
for(int num:nums1){
hash[num]=1;
}
for(int num:nums2){
if(hash[num]==1){
result_set.insert(num);
}
}
return vector<int>(result_set.begin(),result_set.end());
}
};
202. 快乐数
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;
while(1){
int sum = get_sum(n);
if(sum == 1){
return true;
}
if(set.find(sum) != set.end()){
return false;
}else{
set.insert(sum);
}
n = sum;
}
}
};
1. 两数之和
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 {iter->second, i};
}
map.insert(pair<int, int>(nums[i], i));
}
return {};
}
};