当前位置:网站首页>leetcode刷题 (5.28) 哈希表
leetcode刷题 (5.28) 哈希表
2022-07-06 08:14:00 【Freya】
1. 有效的字母异位词
题目:
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。
输入: s = "anagram", t = "nagaram"
输出: true
输入: s = "rat", t = "car"
输出: false
思路:
用一个长度为26的数组表示哈希表,s中字母在哈希表中对应位置(s[i] - ‘a’)加一,t中字母再依次减一,最后看哈希表是否全为0,否则false.
笔记:
当遇到了要快速判断一个元素是否出现集合里的时候,就要考虑哈希法。
但是哈希法也是牺牲了空间换取了时间,因为要使用额外的数组,set或者是map来存放数据,才能实现快速的查找。
当要使用集合来解决哈希问题的时候,优先使用unordered_set,因为它的查询和增删效率是最优的,如果需要集合是有序的,那么就用set,如果要求不仅有序还要有重复数据的话,那么就用multiset。
python中ord()表示取ASCII值。
C++:
// 时间复杂度为O(n), 空间复杂度O(1)
class Solution {
public:
bool isAnagram(string s, string t) {
int record[26] = {
0};
for(int i = 0; i < s.size(); i++){
record[s[i] - 'a']++;
}
for(int i = 0; i < t.size(); i++){
record[t[i] - 'a']--;
}
for(int i = 0; i < 26; i++){
if(record[i] != 0){
return false;
}
}
return true;
}
};
Python:
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
record = [0] * 26
for i in range(len(s)):
record[ord(s[i]) - ord("a")] += 1
for i in range(len(t)):
record[ord(t[i]) - ord("a")] -= 1
for i in range(26):
if record[i] != 0:
return False
break
return True
2. 两个数组的交集
题目:
给定两个数组 nums1 和 nums2 ,返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
解释:[4,9] 也是可通过的
思路:
C++:
用unordered_set实现
注意:直接使用set 不仅占用空间比数组大,而且速度要比数组慢(所以能用数组还是尽量用数组)
Python:
两个数组变为两个集合,集合求交集,再还原为数组(list)
笔记:
C++:
- for ( : ) 用于遍历数组
- unordered_set::find()函数是C++ STL中的内置函数,用于在容器中搜索元素。
返回找到元素的迭代器,否则返回指向unordered_set末尾的迭代器。
Python:
& :集合求交集
C++:
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> result_set;
unordered_set<int> nums_set(nums1.begin(), nums1.end());
for (int num : nums2) {
// 常用find和end组合来判断num_set中是否含有num
// 如果nums_set中含有nums2中的元素就把它插到result_set中
// 这里nums_set是nums1转化得来(去重)
if (nums_set.find(num) != nums_set.end()){
result_set.insert(num);
}
}
return vector<int> (result_set.begin(), result_set.end());
}
};
Python:
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
边栏推荐
- What is the use of entering the critical point? How to realize STM32 single chip microcomputer?
- 1202 character lookup
- 22. Empty the table
- File upload of DVWA range
- Introduction to backup and recovery Cr
- Restore backup data on S3 compatible storage with tidb lightning
- Vocabulary notes for postgraduate entrance examination (3)
- Chinese Remainder Theorem (Sun Tzu theorem) principle and template code
- From monomer structure to microservice architecture, introduction to microservices
- Data governance: Data Governance under microservice architecture
猜你喜欢

Learn Arduino with examples

File upload of DVWA range

ROS learning (IX): referencing custom message types in header files

化不掉的钟薛高,逃不出网红产品的生命周期

"Designer universe" Guangdong responds to the opinions of the national development and Reform Commission. Primary school students incarnate as small community designers | national economic and Informa

指针和数组笔试题解析

Go learning notes (3) basic types and statements (2)

Asia Pacific Financial Media | "APEC industry +" Western Silicon Valley invests 2trillion yuan in Chengdu Chongqing economic circle to catch up with Shanghai | stable strategy industry fund observatio

21. Delete data

Use Alibaba icon in uniapp
随机推荐
Yyds dry goods inventory three JS source code interpretation eventdispatcher
[Yugong series] February 2022 U3D full stack class 010 prefabricated parts
Nacos Development Manual
Use Alibaba icon in uniapp
A Closer Look at How Fine-tuning Changes BERT
NFT smart contract release, blind box, public offering technology practice -- contract
Go learning notes (3) basic types and statements (2)
Data governance: Data Governance under microservice architecture
远程存储访问授权
Mex related learning
Leetcode question brushing record | 203_ Remove linked list elements
Onie supports pice hard disk
Machine learning - decision tree
Asia Pacific Financial Media | "APEC industry +" Western Silicon Valley invests 2trillion yuan in Chengdu Chongqing economic circle to catch up with Shanghai | stable strategy industry fund observatio
C language custom type: struct
"Designer universe" Guangdong responds to the opinions of the national development and Reform Commission. Primary school students incarnate as small community designers | national economic and Informa
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
Common functions for PHP to process strings
Data governance: data quality
IP lab, the first weekly recheck