当前位置:网站首页>Leetcode question brushing (5.28) hash table
Leetcode question brushing (5.28) hash table
2022-07-06 08:20:00 【Freya】
1. Effective alphabetic words
subject :
Given two strings s and t , Write a function to determine t Whether it is s Letter heteronym of .
Be careful : if s and t Each character in the has the same number of occurrences , said s and t They are mutually alphabetic words .
Input : s = "anagram", t = "nagaram"
Output : true
Input : s = "rat", t = "car"
Output : false
Ideas :
Use a length of 26 Array of represents hash table ,s The corresponding position of the middle letter in the hash table (s[i] - ‘a’) Add one ,t The middle letters are then subtracted by one , Finally, check whether the hash table is all 0, otherwise false.
note :
When it comes to quickly determining whether an element appears in the set , Think about hashifa .
But hashifa also sacrificed space for time , Because you need to use extra arrays ,set Or is it map To store data , In order to achieve fast search .
When it comes to using collections to solve hash problems , priority of use unordered_set, Because its query and add delete efficiency is optimal , If you need the set to be ordered , Then use set, If it requires not only order but also duplicate data , Then use multiset.
python in ord() It means take ASCII value .
C++:
// The time complexity is O(n), Spatial complexity 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. Intersection of two arrays
subject :
Given two arrays nums1 and nums2 , return Their intersection . Every element in the output must be only Of . We can Regardless of the order of the output results .
Input :nums1 = [1,2,2,1], nums2 = [2,2]
Output :[2]
Input :nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output :[9,4]
explain :[4,9] It is also passable
Ideas :
C++:
use unordered_set Realization
Be careful : Use it directly set Not only does it take up more space than arrays , And it's slower than arrays ( So can we use arrays or try to use arrays )
Python:
Two arrays become two sets , Intersection of sets , Then revert to array (list)
note :
C++:
- for ( : ) For traversing arrays
- unordered_set::find() The function is C++ STL Built in functions in , Used to search for elements in containers .
Returns the iterator that found the element , Otherwise, it points back to unordered_set Iterator at the end .
Python:
& : Intersection of sets
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) {
// Commonly used find and end Combine to judge num_set Whether contains num
// If nums_set contains nums2 Insert it into result_set in
// here nums_set yes nums1 Converted ( duplicate removal )
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))
边栏推荐
- 649. Dota2 Senate
- Asia Pacific Financial Media | female pattern ladyvision: forced the hotel to upgrade security. The drunk woman died in the guest room, and the hotel was sentenced not to pay compensation | APEC secur
- Introduction to number theory (greatest common divisor, prime sieve, inverse element)
- Online yaml to CSV tool
- Oracle time display adjustment
- ESP系列引脚說明圖匯總
- NFT smart contract release, blind box, public offering technology practice -- jigsaw puzzle
- Entity class design for calculating age based on birthday
- Understanding of law of large numbers and central limit theorem
- [research materials] 2021 Research Report on China's smart medical industry - Download attached
猜你喜欢
3. File operation 3-with
The Vice Minister of the Ministry of industry and information technology of "APEC industry +" of the national economic and information technology center led a team to Sichuan to investigate the operat
Analysis of pointer and array written test questions
[cloud native] teach you how to build ferry open source work order system
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
Convolution, pooling, activation function, initialization, normalization, regularization, learning rate - Summary of deep learning foundation
24. Query table data (basic)
在 uniapp 中使用阿里图标
C language - bit segment
Artcube information of "designer universe": Guangzhou implements the community designer system to achieve "great improvement" of urban quality | national economic and Information Center
随机推荐
Permutation and combination function
Hill sort c language
ESP系列引脚说明图汇总
08- [istio] istio gateway, virtual service and the relationship between them
Understanding of law of large numbers and central limit theorem
synchronized 解决共享带来的问题
Analysis of Top1 accuracy and top5 accuracy examples
[research materials] 2021 live broadcast annual data report of e-commerce - Download attached
07- [istio] istio destinationrule (purpose rule)
[Yugong series] February 2022 U3D full stack class 011 unity section 1 mind map
Webrtc series-h.264 estimated bit rate calculation
LDAP Application Section (4) Jenkins Access
MFC 给列表控件发送左键单击、双击、以及右键单击消息
A Closer Look at How Fine-tuning Changes BERT
ESP series pin description diagram summary
【MySQL】数据库的存储过程与存储函数通关教程(完整版)
化不掉的钟薛高,逃不出网红产品的生命周期
从 CSV 文件迁移数据到 TiDB
Asia Pacific Financial Media | designer universe | Guangdong responds to the opinions of the national development and Reform Commission. Primary school students incarnate as small community designers
Oracle time display adjustment