时间复杂度-将映射条目复制到Arraylist

时间:2019-01-22 17:20:08

标签: java arraylist collections hashmap time-complexity

我一直在寻找一种有效的方法来按其值对哈希表进行排序,并且遇到了一些解决方案,这些解决方案通过将条目复制到列表并按值对列表进行排序来声明为O(n log n)。复制回LinkedHashMap。我以为这可能是O(n ^ 2)而不是O(n log n)。

List<Entry<K, V>> entries = new ArrayList<Entry<K, V>>(map.entrySet());

我想确认上面代码的时间复杂度是否为O(n ^ 2)?

这是我的理解:我们通过映射的条目进行迭代(这是O(n)),当我们将每个条目添加到列表中时,它就会添加到列表的末尾以及执行操作所需的时间这也将是O(n)并使它成为O(n ^ 2)。

这正确吗?

1 个答案:

答案 0 :(得分:3)

  1. 执行var DATA = {"device_groups":[{"id":"1","name":"group 1","devices":[{"id":11,"name":"device 11","active":1},{"id":12,"name":"device 12","active":0},{"id":13,"name":"device 13","active":0}]},{"id":"2","name":"group 2","devices":[{"id":21,"name":"device 21","active":1},{"id":22,"name":"device 22","active":0},{"id":23,"name":"device 23","active":1}]},{"id":"3","name":"group 3","devices":[{"id":31,"name":"device 31","active":1},{"id":32,"name":"device 32","active":0},{"id":33,"name":"device 33","active":1}]}]}; var devices = DATA.device_groups .reduce((acc, ele) => { acc = acc.concat([...ele['devices']]); //merging each device array with the next with the concat(). return acc; },[]) .filter((data) => data['active'] === 1); console.log(devices);为O(n)。 new ArrayList<Entry<K, V>>(map.entrySet())将与map.entrySet()转换为Entry[]。没有通常的toArray()那样的常规追加和调整大小。

  2. 由于TimSort,对add()进行排序的结果为O(n log n)。

  3. ArrayList创建new LinedHashMap是O(n)。

整个方法将是O(n log n),因为排序将是主要操作。