Leetcode242(代码随想录:有效的字母异位词)
哈希表(Hash Table):一般用于快速判断一个元素是否出现在集合里。
C++:
一、vector对象: vector<int> nums;
1. 求vector数组长度:nums.size();
2. 在数组尾部插入元素elem:nums.push_back(elem);
3. 删除数组尾部最后一个元素:nums.pop_back();
4. 删除位置pos的元素:nums.erase(const pos);
5. 删除位置begin到end之间的元素:nums.erase(const begin, const end);
6. 创建vector数组:
(1)一维:vector<int> result(nums.size(), 0);初始化元素值为0,元素个数为nums.size()的一维数组;
(2)二维:vector<vector<int>> result(row, vector<int>(column, 0));初始化row*column的二维数组,初始化值为0;
7. 数组第一个元素:nums.begin();
8. 数组最后一个元素:nums.end();
9. 使用sort对数组进行排序需要包含头文件#include<algorithm>:
(1)对数组升序排序:sort(nums.begin(), nums.end());
(2)对数组降序排序:sort(nums.begin(), nums.end(), greater<int>());
10. std::cout不能直接输出整个vector数组,需要对vector数组遍历依次输出;
二、知识:
1. INT32_MAX:需要#include<limits.h>,是一个宏定义,数值等于2147483647;
class Solution {
public:
bool isAnagram(string s, string t) {
vector<int> hash(26, 0);
for(int i = 0; i < s.size(); i++)
{
hash[s[i] - 'a'] += 1;
}
for(int i = 0; i < t.size(); i++)
{
hash[t[i] - 'a'] -= 1;
}
for(int i = 0; i < 26; i++)
if(hash[i] != 0) return false;
return true;
}
};
Python:
1. python求数组nums长度:
len(nums)
2. python取整:
middle = (left + right) // 2
3. python移除数组nums中的元素val:
nums.remove(val)
4.(1)python升序排序,列表本身修改:
nums.sort()
(2)python升序排序,返回新列表:
sorted(nums)
5.(1)列表地址相同:result = nums
(2)创建列表副本:result = nums[:]
6.(1)float('inf'):正无穷大
(2)float('-inf'):负无穷大
7.(1)建立二维列表的方法:result = [[0] * n for _ in range(n)]
(2)建立一维全0列表的方法:result = [0 for _ in range(n)]
8. ord():python内置函数,用于返回字符的Unicode码
9. collections模块中的defaultdict:可以设置默认值的字典dict,defaultdict的第一个参数是一个可调用对象,它用于生成默认值,例如int, list, set等。
10. collections模块中的Counter:Counter是一个简单的计数器,例如,统计字符出现的个数
(1)elements()方法:返回一个迭代器,可以通过 list 或者其它方法将迭代器中的元素输出,输出的结果为对应出现次数的元素
(2)most_common()方法:返回一个出现次数从大到小的前 n 个元素的列表
方法一(和C++对应,不使用python包):
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
hash = [0 for _ in range(26)]
for i in range(len(s)):
hash[ord(s[i]) - ord('a')] += 1
for j in range(len(t)):
hash[ord(t[j]) - ord('a')] -= 1
for k in range(26):
if hash[k] != 0:
return False
return True
方法二(from collections import defaultdict):
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
from collections import defaultdict
s_dict = defaultdict(int)
t_dict = defaultdict(int)
for i in s:
s_dict[i] += 1
for j in t:
t_dict[j] += 1
return s_dict == t_dict
方法三(from collections import Counter):
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
from collections import Counter
s_count = Counter(s)
t_count = Counter(t)
return s_count == t_count