(第五天休息)
题目链接:242. 有效的字母异位词 - 力扣(LeetCode)
这道题我是采用暴力解法; 要循环l两次;
bool isAnagram(std::string s, std::string t) {
int lens = s.length(),lent = t.length();
if(lens != lent)return 0;
int a[26] = {0};
for(int i = 0;i
题目链接:349. 两个数组的交集 - 力扣(LeetCode)
思路: 遍历数组 。set 存放
class Solution {
public:
vector intersection(vector& nums1, vector& nums2) {
std::set mySet;
std::vector ans = {};
for(int x:nums1){
mySet.insert(x);
}
for(int x:nums2){
if(mySet.find(x) != mySet.end()){
mySet.erase(x);// 在mySet删去此 数,避免重复添加进ans
ans.push_back(x);
}
}
return ans;
}
};
题目链接:202. 快乐数 - 力扣(LeetCode)
思路 暴力计算? 看了一下 Carl 哥的思路 发现没有注意到题目中 可能无解的情况 比如 :9-81-9-81 等等…
91-82-68-100
所以暴力是不可能暴力的,在这种情况下暴力是很复杂的。
由此我们可以使用容器将计算过程中出现的数字记录下来。只要检查这个数在不在容器中就能判断是否无解。
class Solution {
public:
int getSum(int n){
int ans = 0;
while(n!=0){
int a = n%10;
ans += a*a;
n /= 10;
}
return ans;
}
bool isHappy(int n) {
std::set mySet;
while(1){
int ans = getSum(n);
if(ans == 1){return 1;}
if(mySet.find(ans) != mySet.end()){
return 0;
}else{
mySet.insert(ans);
}
n = ans;
}
}
};
题目链接:1. 两数之和 - 力扣(LeetCode)
思路: 使用 map 记录遍历过的 数字和下标
当在map中找到一个元素满足条件时,将其下标和当前在vector中遍历的下标添加进 vector;
如果当前元素在map中没有符合元素的,将当前元素以及下表填进map;
class Solution {
public:
vector twoSum(vector& nums, int target) {
std::map myMap;
std::vector arr;
size_t i = 0;
for(int val:nums){
if(myMap.find(target - val) != myMap.end()){// 存在 val 与其和为target 的元素。
arr.push_back(i);
arr.push_back(myMap[target-val]);
return arr;
}
myMap[val] = i;
i++;
}
return arr;
}
};