现在我有以下 javascript 字典
var a = {};
a['SVG343'] = 1942;
a['UAL534'] = 2153;
右边的数字代表时间,键是唯一的 ID。我想让 id 成为键,因为它们是唯一的。我的问题是给出一个时间找到对应的id。我要如何做到这一点是遍历字典中的每个条目,直到找到正确的时间并使用当前的密钥来获取 id。
然而我担心性能,我的问题是,遍历字典中的每个条目(O(n))是否比任何其他方法都慢得多?
您可以根据时间建立索引:
var indexByTimes = {};
for (var prop in a) {
if (a.hasOwnProperty(prop)) {
indexByTimes[a[prop]] = prop;
}
}
对于多个时间值,请使用 ID 数组:
for (var prop in a) {
if (a.hasOwnProperty(prop)) {
if (indexByTimes.hasOwnProperty(a[prop])) {
indexByTimes[a[prop]].push(prop);
} else {
indexByTimes[a[prop]] = [prop];
}
}
}
然后你可以访问与 1942 年时间相对应的所有 IDindexByTimes['1942']
时间复杂度为 O(1)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)