假设我们有一个包含整数的列表,我们需要找到最小值和最大值。最好的方法是什么?我可以想到以下内容:
If number of reads are much higher than writes; keep the list in sorted manner. Whenever a number is added; add it in sorted manner. Now to get min and max we can just get first and last element of this list.
If number of writes are higher than reads; iterate on the list and return result. But this is O(n) which looks to be expensive.
还有其他更好的方法吗?
最佳答案
假设您可以观察到列表的任何变化,您可以存储(缓存)最小值和最大值,并可能在添加/删除数字时更新缓存值。此时,列表的顺序无关紧要。
关于java - 从列表中获取最小和最大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14726565/