1、LeetCode242
C
bool isAnagram(char * s, char * t){
// 提前将strlen()函数的值赋给变量,能减少运行时间
int len_s = strlen(s), len_t = strlen(t);
// 按以下写法,一定要对比s与t的长度:s("ac"),t("a")
if (len_t != len_s) return false;
int hash[26];
/* 初始化hash数组为0;
* void *memset(void* s, int c, unsigned long n);
* 将指针变量s所指向的前n个字节的内存单元用一个“整数”c替换,可以为任何数据类型的数据进行初始化。
*/
memset(hash, 0 , sizeof(hash));
for (int i = 0; i < len_s; i++) {
hash[s[i] - 'a']++;
}
for (int i = 0; i < len_t; i++) {
hash[t[i] - 'a']--;
if (hash[t[i] - 'a'] < 0) return false;
}
return true;
}
2、LeetCode349
转C++了,C做这个太痛苦了,用C实现unordered_set,时间上太紧迫
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> hash;
vector<int> result;
for (auto i: nums1) {
hash.insert(i);
}
for (auto i: nums2) {
if (hash.count(i) != 0) {
result.push_back(i);
hash.erase(i);
}
}
return result;
}
};
3、LeetCode202
class Solution {
public:
int getSum(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 temp;
while (true) {
temp = getSum(n);
if (temp == 1) return true;
if (hash.find(temp) == hash.end()) {
hash.insert(temp);
} else {
return false;
}
n = temp;
}
}
};
4、LeetCode1
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
unordered_map<int, int> map;
for (int i = 0; i < nums.size(); i++) {
if (map.count(target - nums[i])) {
result.push_back(map.at(target - nums[i]));
result.push_back(i);
return result;
} else {
map.insert(pair<int, int>(nums[i], i));
}
}
return result;
}
};