Java数据结构的矩阵?
我可以用于包含短变量但大多数元素为空的矩阵的最佳数据结构是什么。
我可以简单地使用 n by b 数组作为矩阵,但问题是我不想浪费内存因为矩阵中只有几个元素..
我打算使用链表或哈希表,但不确定哪一个是最好的数据结构以及如何实现这一点..
What is the best data structure I can use for my matrix that will contain short variables but most of elements are empty..
I could simply use n by b array for the matrix but the problem is that I don't want to waste the memory because only a few elements are in the matrix..
I was going to use a linked list or a hash table but not sure which one would be the best data structure and how to implemente this..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我将实现一个稀疏矩阵。使用以行索引作为键的
HashMap
,然后使用HashMap
或TreeMap
作为实际元素(以列索引作为键) 。如果您要存储原始类型,我建议您查看 Trove Java Collections Framework。它针对与原始类型一起使用进行了优化。无论如何,我建议使用它,因为密钥可能都是原始的。I would implement a Sparse Matrix. Use a
HashMap
with the row index as keys, and then either aHashMap
orTreeMap
for the actual elements (with the column index as key). If you are storing primitive types, I would suggest having a look at the Trove Java Collections Framework. It is optimized for use with primitive types. I would suggest using it anyway, as the keys could all be primitive.Google Guava 库还提供了多个 Table 实现
There are also multiple Table implementations from Google Guava libraries
当矩阵稀疏时,最好使用LinkedList。在空间方面,LinkedList 会比其他选项更好(假设矩阵是稀疏的)。
但请注意,LinkedList 的访问时间为 O(n)。
When the matrix is sparse, its better to use LinkedList. LinkedList will be better than other options in terms of space(provided the matrix is sparse).
But note that LinkedList has O(n) time for access.