当前位置:网站首页>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下载安装教程(Win10系统)
- 好用的TCP-UDP_debug工具下载和使用
- Machine learning - decision tree
- Circuit breaker: use of hystrix
- 从 SQL 文件迁移数据到 TiDB
- ROS learning (IX): referencing custom message types in header files
- Restore backup data on S3 compatible storage with br
- 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
- On why we should program for all
- Common functions for PHP to process strings
猜你喜欢

ESP系列引脚说明图汇总

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

Leetcode question brushing record | 203_ Remove linked list elements

ESP series pin description diagram summary

The State Economic Information Center "APEC industry +" Western Silicon Valley will invest 2trillion yuan in Chengdu Chongqing economic circle, which will surpass the observation of Shanghai | stable

Yyds dry goods inventory three JS source code interpretation eventdispatcher

指针和数组笔试题解析
![[cloud native] teach you how to build ferry open source work order system](/img/fb/507f763791235bd00bc8201e5d7741.png)
[cloud native] teach you how to build ferry open source work order system

National economic information center "APEC industry +": economic data released at the night of the Spring Festival | observation of stable strategy industry fund

From monomer structure to microservice architecture, introduction to microservices
随机推荐
Easy to use tcp-udp_ Debug tool download and use
flask返回文件下载
指针和数组笔试题解析
Wireshark grabs packets to understand its word TCP segment
Golang DNS write casually
[research materials] 2021 China online high growth white paper - Download attached
NFT smart contract release, blind box, public offering technology practice -- contract
. Net 6 learning notes: what is NET Core
Epoll and IO multiplexing of redis
WebRTC系列-H.264预估码率计算
华为云OBS文件上传下载工具类
【云原生】手把手教你搭建ferry开源工单系统
Secure captcha (unsafe verification code) of DVWA range
Chinese Remainder Theorem (Sun Tzu theorem) principle and template code
Char to leading 0
A Closer Look at How Fine-tuning Changes BERT
C语言 - 位段
The resources of underground pipe holes are tight, and the air blowing micro cable is not fragrant?
Day29-t77 & t1726-2022-02-13-don't answer by yourself
Tidb backup and recovery introduction