Merge pull request #2209 from niuli1991/master

添加1002.查找常用字符 Ruby实现
This commit is contained in:
程序员Carl
2023-08-08 09:23:34 +08:00
committed by GitHub
2 changed files with 67 additions and 0 deletions

View File

@ -465,6 +465,25 @@ object Solution {
}
```
###Ruby
```ruby
def intersection(nums1, nums2)
hash = {}
result = {}
nums1.each do |num|
hash[num] = 1 if hash[num].nil?
end
nums2.each do |num|
#取nums1和nums2交集
result[num] = 1 if hash[num] != nil
end
return result.keys
end
```
## 相关题目
* [350.两个数组的交集 II](https://leetcode.cn/problems/intersection-of-two-arrays-ii/)

View File

@ -525,6 +525,54 @@ impl Solution {
}
```
Ruby:
```ruby
def common_chars(words)
result = []
#统计所有字符串里字符出现的最小频率
hash = {}
#初始化标识
is_first = true
words.each do |word|
#记录共同字符
chars = []
word.split('').each do |chr|
#第一个字符串初始化
if is_first
chars << chr
else
#字母之前出现过的最小次数
if hash[chr] != nil && hash[chr] > 0
hash[chr] -= 1
chars << chr
end
end
end
is_first = false
#清除hash更新字符最小频率
hash.clear
chars.each do |chr|
if hash[chr] != nil
hash[chr] += 1
else
hash[chr] = 1
end
end
end
#字符最小频率hash转换为字符数组
hash.keys.each do |key|
for i in 0..hash[key] - 1
result << key
end
end
return result
end
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>