242.有效的字母异位词
LeetCode题目
注意事项
class Solution {
public:
bool isAnagram(string s, string t) {
int data[26] = {0};
for (int i = 0; i < s.length(); i++)
data[int(s[i]) - int('a')]++;
for (int i = 0; i < t.length(); i++)
data[int(t[i]) - int('a')]--;
for (int i = 0; i < 26; i++) {
if (data[i] != 0)
return false;
}
return true;
}
};
349. 两个数组的交集
LeetCode题目
注意事项
- 效率:array > unordered_set > set
- unordered_set函数:insert, find, erase, count 等
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> result_set;
unordered_set<int> nums1_set(nums1.begin(), nums1.end());
for (int num : nums2) {
if (nums1_set.find(num) != nums1_set.end()) {
result_set.insert(num);
}
}
return vector<int>(result_set.begin(), result_set.end());
}
};
202. 快乐数
LeetCode题目
注意事项
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> data;
int num = n, sum = 0;
while (true) {
while (num > 0) {
sum += (num % 10) * (num % 10);
num /= 10;
}
if (sum == 1)
return true;
else if (data.find(sum) != data.end())
return false;
else {
data.insert(sum);
num = sum;
sum = 0;
}
}
}
};
1. 两数之和
LeetCode题目
注意事项
- unordered_map插入方式:
1.map.insert(pair<,>(key, value));
2.map.insert(unordered_map<,>::value_type(key, value));
3.map[key] = value;
- unordered_map查找方式:
1.map.count(key) == 0;
2.iter = map.find(key) / iter.first / iter.second
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> map;
for (int i = 0; i < nums.size(); i++) {
int target1 = target - nums[i];
auto index = map.find(target1);
if (index != map.end()) return {index->second, i};
else map.insert(pair<int, int>(nums[i], i));
}
return {};
}
};