[英]Is there a more efficient algorithm to flatten an array?
I am aware of the recursive way to flatten a nested array. 我知道扁平化嵌套数组的递归方法。 There are several solutions on stackoverflow (both in java and javascript - some using built in libraries). 有许多关于stackoverflow的解决方案(包括Java和javascript-有些使用内置库)。
But the time complexity of these solutions is O(n^2)! 但是这些解决方案的时间复杂度是O(n ^ 2)! I was wondering if there is an algorithm which could do better. 我想知道是否有一种算法可以做得更好。
Thanks in advance for your help! 在此先感谢您的帮助!
You are either mistaken or you define your n as the root square of number of elements to process. 您可能会误解,或者将n定义为要处理的元素数量的平方根。
All the sane solutions of the array flattening problem are O(n), where n depends on the total number of elements (because, essentially, you need to scan them all, each of them only once). 数组展平问题的所有合理解决方案都是O(n),其中n取决于元素的总数(因为从本质上讲,您需要扫描所有元素,每个元素仅扫描一次)。 Flattening an array is not an algorithmic problem, it's just the question of getting it in an "elegant" snippet. 展平数组不是算法问题,而仅仅是将其放入“优雅”代码段中的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.