目录
242-有效的字母异位词
输入: s = "anagram", t = "nagaram" 输出: true输入: s = "rat", t = "car" 输出: false
提交代码:先排序,排序后是相同的,直接比较;
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
if(s == t){
return true;
}
else{
return false;
}
}
};
349-两个数组的交集
输入:nums1 = [1,2,2,1], nums2 = [2,2] 输出:[2]输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出:[9,4] 解释:[4,9] 也是可通过的
思路:
1、使用哈希表将一个数组元素全部保存;
2、遍历另一个数组,在哈希表中查找每个元素;
3、如果找到,将该元素保存至哈希表(要求输出为数组,但不能重复,所以先存在哈希表里去重);
4、将哈希表元素存入数组;
提交代码
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> st;
unordered_set<int> retSt;
vector<int> retVec;
if(nums1.size() > nums2.size()){
for(auto e : nums2){
st.emplace(e);
}
for(auto e : nums1){
if(st.end() != st.find(e)){
retSt.insert(e);
}
}
for(auto e : retSt){
retVec.emplace_back(e);
}
return retVec;
}
else{
for(auto e : nums1){
st.emplace(e);
}
for(auto e : nums2){
if(st.end() != st.find(e)){
retSt.insert(e);
}
}
for(auto e : retSt){
retVec.emplace_back(e);
}
return retVec;
}
}
};
202-快乐数
输入:n = 19 输出:true 解释: 1^2 + 9^2 = 82 8^2 + 2^2 = 68 6^2 + 8^2 = 100 1^2 + 0^2 + 0^2 = 1输入:n = 2 输出:false 解释: 2^2 = 4 4^2 = 16 1^2 + 6^2 = 37 3^2 + 7^2 = 58 5^2 + 8^2 = 89 8^2 + 9^2 = 145 1^2 + 4^2 + 5^2 = 42 4^2 + 2^2 = 20 2^2 + 0 = 4 //重复,开始循环
根据我们的探索,我们猜测会有以下三种可能:
- 最终会得到 1。
- 最终会进入循环。
- 值会越来越大,最后接近无穷大。
第三个情况比较难以检测和处理。
力扣官方解释:
我们怎么知道它会继续变大,而不是最终得到1呢?我们可以仔细想一想,每一位数的最大数字的下一位数是多少。
自己瞎解释:
举例:
current next next
9 81 64 + 1 = 65
9999999999(10个9) 81 * 10 = 810 64 + 1 + 0 = 65
999....99(100个9) 81 * 100 = 8100 64 + 1 + 0 + 0 = 65
从上面的例子可见,对于一个当前的数current,它的位数每升一个数量级,它的next肯定会有一个降级,因为*10之后肯定会有一个0存在;从这个例子大概可以解释为什么不快乐数不是无限增大,而是一个循环了吧!!
不快乐数不是无限增大,而是一个循环了吧!!!!!
也就是:“3、值会越来越大,最后接近无穷大。”这种情况不存在!
那么只剩两种情况:
- 最终会得到 1。
- 最终会进入循环。
那么思路:
1、生成平方和;
2、判断平方和是否已经存在过
存在:说明循环,返回false;
不存在:继续while循环,直到平方和为1(返回true)或者循环;
提交代码
class Solution {
public:
bool isHappy(int n) {
int sum = n;
unordered_set<int> st;
while(sum != 1){ //sum != 1
vector<int> vec;
while(sum){ //生成平方和vector
vec.emplace_back((sum % 10) * (sum % 10));
sum /= 10;
}
sum = 0;
for(auto e : vec){//求新的sum
sum += e;
}
if(st.end() != st.find(sum)){
return false; //哈希表中已有此sum,说明sum产生了循环,sum不可能为1了
}
st.emplace(sum); //sum放入哈希表
}
return true; //sum == 1
}
};
1-两数之和
输入:nums = [3,2,4], target = 6 输出:[1,2]输入:nums = [3,3], target = 6 输出:[0,1]
两种解法:
一、遍历所有和的可能性;
二、使用哈希表存储数组元素,查找target - num[i];
class Solution {
public:
//哈希表
vector<int> twoSum(vector<int>& nums, int target) {
int size = nums.size();
unordered_map<int,int> hashtab;
for(int i = 0; i < size; ++i)
{
auto it = hashtab.find(target - nums[i]);
if(it != hashtab.end())
{
return{it->second, i};
}
hashtab.insert(make_pair(nums[i], i));
}
return {};
}
//暴力解法
// vector<int> twoSum(vector<int>& nums, int target) {
// int size = nums.size();
// for(int i = 0; i < size; ++i)
// {
// for(int j = i + 1; j < size; ++j)
// {
// if(target == nums[i] + nums[j])
// {
// return {i, j};
// }
// }
// }
// return {};
// }
};