当前位置: 首页> 汽车> 时评 > 代码随想录-DAY⑤-哈希表——leetcode 242 | 349 | 202

代码随想录-DAY⑤-哈希表——leetcode 242 | 349 | 202

时间:2025/7/12 9:22:20来源:https://blog.csdn.net/weixin_43160551/article/details/140280469 浏览次数: 0次

242

思路

先遍历字符串1,
记录每个字符的个数,
然后遍历字符串2,
挨个减去字符个数,
出现小于零的个数说明字符总数不重合。

时间复杂度:O(n)
空间复杂度:O(1)

代码
class Solution {
public:bool isAnagram(string s, string t) {if(s.length() != t.length()){return false;}vector<int> table(26, 0);for(auto c : s){table[c-'a']++;}for(auto c : t){table[c-'a']--;if(table[c-'a']<0){return false;}}return true;}
};

349

思路

先把数组1存到哈希表1中,
然后遍历数组2,
将能在哈希表1中找到的存到哈希表2中,
这样可以去掉重复的,
最后把哈希表2转为数组。

时间复杂度: O(n + m)
空间复杂度: O(n)

代码
class Solution {
public:vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {unordered_set<int> nums1_set(nums1.begin(), nums1.end());unordered_set<int> result_set;for(auto i : nums2){if(nums1_set.count(i)){result_set.insert(i);}}return vector<int>(result_set.begin(), result_set.end());}
};

202

思路

申请一个哈希表,
每计算一次快乐数,
都将结果存到哈希表中,
如果发现重复结果说明不是快乐数,
如果发现结果值为1说明是快乐数。

时间复杂度: O(logn)
空间复杂度: O(logn)

代码
class Solution {
public:int getnext(int n) {int num=0;while(n>0){num += (n%10)*(n%10);n /= 10;}return num;}bool isHappy(int n) {unordered_set<int> nums;while(n!=1){if(nums.count(n)){return false;}nums.insert(n);n = getnext(n);}return true;}
};
关键字:代码随想录-DAY⑤-哈希表——leetcode 242 | 349 | 202

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: