242.有效的字母异位词
Python
from collections import Counter
class Solution:def isAnagram(self, s: str, t: str) -> bool:n=Counter(s)m=Counter(t)return n==m
C++
class Solution {
public:bool isAnagram(string s, string t) {int Map[26]={0};for (int i=0;i<s.size();i++)Map[s[i]-'a']++;for (int i=0;i<t.size();i++)Map[t[i]-'a']--;for (int i=0;i<26;i++)if (Map[i]!=0)return false;return true;}
};
349.两个数组的交集
Python
class Solution:def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:nums1=set(nums1)res=set()for i in range(len(nums2)):if nums2[i] in nums1:res.add(nums2[i])return list(res)
C++
class Solution {
public:vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {unordered_set<int> res;unordered_set<int> nums_set(nums1.begin(),nums1.end());for (int num:nums2){if (nums_set.find(num)!=nums_set.end()){res.insert(num);}}return vector<int>(res.begin(),res.end());}
};
202. 快乐数
C++
class Solution {
public:int check(int num){int total=0;while (num>=1){total+=(num%10)*(num%10);num/=10;}return total;}bool isHappy(int n) {unordered_set<int>mp;while(true){if (n==1)return true;else{if (mp.find(n)!=mp.end())return false;else {mp.insert(n);n=check(n);}}}}
};
Python
class Solution:def check(self,n):nums=map(int,list(str(n)))total=0for i in nums:total+=i**2return totaldef isHappy(self, n: int) -> bool:s=set() #表示mapwhile 1:if n==1:return Trueif n in s:return Falseelse:s.add(n)n=self.check(n)
总结
思路都是知道的,就是C++的代码还不是特别熟练。