mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 15:09:40 +08:00
0454.四数相加II.html 增加Ruby版本实现
This commit is contained in:
@ -488,6 +488,44 @@ int fourSumCount(int* nums1, int nums1Size, int* nums2, int nums2Size, int* nums
|
||||
}
|
||||
```
|
||||
|
||||
### Ruby:
|
||||
|
||||
```ruby
|
||||
# @param {Integer[]} nums1
|
||||
# @param {Integer[]} nums2
|
||||
# @param {Integer[]} nums3
|
||||
# @param {Integer[]} nums4
|
||||
# @return {Integer}
|
||||
# 新思路:和版主的思路基本相同,只是对后面两个数组的二重循环,用一个方法调用外加一重循环替代,简化了一点。
|
||||
# 简单的说,就是把四数和变成了两个两数和的统计(结果放到两个 hash 中),然后再来一次两数和为0.
|
||||
# 把四个数分成两组两个数,然后分别计算每组可能的和情况,分别存入 hash 中,key 是 和,value 是 数量;
|
||||
# 最后,得到的两个 hash 只需要遍历一次,符合和为零的 value 相乘并加总。
|
||||
def four_sum_count(nums1, nums2, nums3, nums4)
|
||||
num_to_count_1 = two_sum_mapping(nums1, nums2)
|
||||
num_to_count_2 = two_sum_mapping(nums3, nums4)
|
||||
|
||||
count_sum = 0
|
||||
|
||||
num_to_count_1.each do |num, count|
|
||||
count_sum += num_to_count_2[-num] * count # 反查另一个 hash,看有没有匹配的,没有的话,hash 默认值为 0,不影响加总;有匹配的,乘积就是可能的情况
|
||||
end
|
||||
|
||||
count_sum
|
||||
end
|
||||
|
||||
def two_sum_mapping(nums1, nums2)
|
||||
num_to_count = Hash.new(0)
|
||||
|
||||
nums1.each do |num1|
|
||||
nums2.each do |nums2|
|
||||
num_to_count[num1 + nums2] += 1 # 统计和为 num1 + nums2 的有几个
|
||||
end
|
||||
end
|
||||
|
||||
num_to_count
|
||||
end
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
|
Reference in New Issue
Block a user