在Swift中通过计数从多维数组中查找最大数组 [英] Find biggest array from a multi dimensional array by count in Swift
问题描述
我有一个多维数组.它本身可以有多个数组.有时可能是 5 或 6.现在我想通过使用数组大小从我的多维数组中获取最大的数组.我不知道如何实现这一目标.因此我在这里发帖.提前致谢.
I has a multi dimensional array. It can have more than one array in itself. Sometimes maybe 5 or 6. Now I want to get the largest array from my multi dimensional array by using array size. I don't know how to achieve this. Hence i'm posting here. Thanks in advance.
例如:
[[["a", "b", "c"], ["d", "e", "f", "g", "h", "i", "j"]]>
[["a", "b", "c"], ["d", "e", "f", "g", "h", "i", "j"]]
推荐答案
如果您正在寻找给定范围内最长的子数组数组然后你可以简单地使用 max(by:)
进行比较使用数组计数:
If you are looking for the longest subarray within the given
array then you can simply use max(by:)
with a comparison
using the array count:
let a = [["a", "b", "c"], ["d", "e", "f", "g", "h", "i", "j"], ["k"]]
let longestSubArray = a.max(by: { $0.count < $1.count })!
print(longestSubArray)
// ["d", "e", "f", "g", "h", "i", "j"]
这里我假设 a
不为空,否则 max(by:)
将返回 nil
.如果发生这种情况,请使用可选绑定:
Here I have assumed that a
is not empty, otherwise max(by:)
will return nil
. If that can happen, use optional binding:
if let longestSubArray = a.max(by: { $0.count < $1.count }) {
print(longestSubArray)
} else {
print("a is empty")
}
备注: Array
是一个 RandomAccessCollection
,因此得到它的 count
是一个 O(1)
操作.
Remark: Array
is a RandomAccessCollection
and therefore getting
its count
is a O(1)
operation.
如果您需要包含最长元素及其索引数组然后你可以将上面的应用到 a.enumerated()
:
If you need both the longest element and its index in the containing
array then you can apply the above to a.enumerated()
:
if let (idx, longest) = a.enumerated().max(by: { $0.element.count < $1.element.count }) {
print("longest subarray", longest)
print("at index", idx)
}
如果最大长度的子数组不止一个,那么上面的解决方案将返回其中之一.@dfri 的回答展示了如何获得全部具有最大长度的子数组.
If there is more than one subarray with the maximal length then the above solutions will return one of them. @dfri's answer shows how to get all subarrays with the maximal length.
这篇关于在Swift中通过计数从多维数组中查找最大数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!