当前位置:网站首页>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))
边栏推荐
- Wincc7.5 download and installation tutorial (win10 system)
- Parameter self-tuning of relay feedback PID controller
- Easy to use tcp-udp_ Debug tool download and use
- "Designer universe": "benefit dimension" APEC public welfare + 2022 the latest slogan and the new platform will be launched soon | Asia Pacific Financial Media
- Summary of phased use of sonic one-stop open source distributed cluster cloud real machine test platform
- Erc20 token agreement
- What is the use of entering the critical point? How to realize STM32 single chip microcomputer?
- Secure captcha (unsafe verification code) of DVWA range
- matplotlib. Widgets are easy to use
- Tidb backup and recovery introduction
猜你喜欢
Personalized online cloud database hybrid optimization system | SIGMOD 2022 selected papers interpretation
[count] [combined number] value series
A Closer Look at How Fine-tuning Changes BERT
Nft智能合约发行,盲盒,公开发售技术实战--拼图篇
Step by step guide to setting NFT as an ens profile Avatar
Esrally domestic installation and use pit avoidance Guide - the latest in the whole network
Codeforces Global Round 19(A~D)
Leetcode question brushing record | 203_ Remove linked list elements
[nonlinear control theory]9_ A series of lectures on nonlinear control theory
C语言 - 位段
随机推荐
C language - bit segment
你想知道的ArrayList知识都在这
[research materials] 2022 China yuancosmos white paper - Download attached
Upgrade tidb operator
synchronized 解决共享带来的问题
1202 character lookup
Use br to back up tidb cluster data to S3 compatible storage
Uibehavior, a comprehensive exploration of ugui source code
数据治理:误区梳理篇
Secure captcha (unsafe verification code) of DVWA range
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
2.10transfrom attribute
matplotlib. Widgets are easy to use
07- [istio] istio destinationrule (purpose rule)
指针和数组笔试题解析
PHP - Common magic method (nanny level teaching)
Learn Arduino with examples
NFT smart contract release, blind box, public offering technology practice -- contract
Artcube information of "designer universe": Guangzhou implements the community designer system to achieve "great improvement" of urban quality | national economic and Information Center
TiDB备份与恢复简介