我有一个多维日期数组,严格来说是ArrayList<ArrayList<Date>>
。我需要生成一个新的单维ArrayList<Date>
,由前面提到的多维数组中的项组成。
我的第一个想法是将所有的arraylists加在一起并对它们进行排序,但由于我不知道每个级别中的元素数量,并且在生成的数组中只需要一定数量的元素,这将是一点点太多的内存和处理器繁重。
我的意思是,如果我加入一个Date
中的所有ArrayList<Date>
元素,我最终会得到一个数千个日期的arraylist ...最终将它修剪为前20个。这就是为什么我放弃了那个解决方案。
那么,我可以使用哪种算法将N(或2)级别的元素排序为1?
修改
ArrayList<Date> a1 = new ArrayList<Date>();
a1.add(new Date(15));
a1.add(new Date(16));
a1.add(new Date(23));
ArrayList<Date> a2 = new ArrayList<Date>();
a2.add(new Date(1));
a2.add(new Date(25));
a2.add(new Date(89));
ArrayList<Date> a3 = new ArrayList<Date>();
a3.add(new Date(64));
a3.add(new Date(72));
a3.add(new Date(73));
ArrayList<ArrayList<Date>> b = new ArrayList<ArrayList<Date>>();
b.add(a1);
b.add(a2);
b.add(a3);
我需要实现一个getLatestDates(ArryList<ArrayList<Date>>, Integer)
,以便返回:
getLatestDates(b, 5) = {Date (89), Date(73), Date(72), Date(64), Date(25)};
在这个例子中只有3 ArrayList
,但在实践中我不知道这个数字,所以我认为移动设备的最佳解决方案是加入所有二级arraylists和排序如果只使用一些项目,那就是新的大项目。
答案 0 :(得分:2)
根据您对问题的描述,我能想到的一些解决方案是:
如果你在几个内部数组中有多个项目,并且你想要前20个,那么你将不得不迭代内部数组以某种方式排序。这些是我能想到的3种解决方案,欢迎任何其他人加入我的帖子。
编辑:
4。 我能想到的另一种方法是:通过扫描整个内部数组数组来构建优先级队列(最小堆)。这将是一个深度限制树,即因为你想要20个元素,树的最大深度可以是4(假设root为0)。堆中允许的项目的最大数量和最大数量为20.这种方法将为您提供O(log N)时间的解决方案。当然,您将花费O(N)时间扫描整个列表中的每个项目,并构建该堆可能占用额外的空间。
答案 1 :(得分:0)
我建议tournament algorithm。这可能非常复杂,但会在总元素数量中为您提供线性运行时间。
我将按以下步骤进行: