242.有效的字母异位词
链接:代码随想录
class Solution { public: bool isAnagram(string s, string t) { //两种做法,一种是int f[26]的数组,一种是map /*第一种,麻烦 unordered_map<int,int>my_map; for(auto ch:s) { my_map[ch]++; } for(auto ch:t) { if(my_map.find(ch)==my_map.end()) { return false; } else { my_map[ch]--; } } for(auto k:my_map) { if(k.second!=0) { return false; } } return true; */ //第二种,int f[26] int f[26]={0}; for(auto ch:s) { f[ch-'a']++; } // s 和 t 中每个字符出现的次数都相同 for(auto ch:t) { if(f[ch-'a']>0) { f[ch-'a']--; } else { return false; } } for(int i=0;i<26;i++) { if(f[i]!=0) { return false; } } return true; } };
349. 两个数组的交集
链接:代码随想录
建议:本题就开始考虑 什么时候用set 什么时候用数组,本题其实是使用set的好题,但是后来力扣改了题目描述和 测试用例,添加了 0 <= nums1[i], nums2[i] <= 1000 条件,所以使用数组也可以了,不过建议大家忽略这个条件。 尝试去使用set。
class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { unordered_set<int>uset(nums1.begin(),nums1.end()); unordered_set<int>uset2(nums2.begin(),nums2.end()); vector<int>v; for(auto p:uset2) { if(uset.find(p)!=uset.end()) { v.push_back(p); } } return v; } };
202. 快乐数
链接:代码随想录
class Solution { //阅读第一遍刷的记录后重写 public: bool isHappy(int n) { unordered_set<int>uset; //记录每次平方和的值,加到uset里,看如若重新出现,则跳出循环 while(uset.find(n)==uset.end()) { uset.insert(n); n=caculate_sum(n); if(n==1) { return true; } } return false; } int caculate_sum(int n) { int temp=n; int sum=0; while(temp) { int r=temp%10; temp/=10; sum+=r*r; } return sum; } };
1. 两数之和
链接:代码随想录
建议:本题虽然是 力扣第一题,但是还是挺难的,也是 代码随想录中 数组,set之后,使用map解决哈希问题的第一题。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int,int> umap; for(int i=0;i<nums.size();i++) { if(umap.find(target-nums[i])!=umap.end()) { return {umap[target-nums[i]],i}; } umap[nums[i]]=i; } vector<int>v; return v; } };