这是一个不会遍历地图中所有元素的解决方案。
这很复杂,我认为它对小型数据集的速度并没有太大的提高。
抱歉,这不是正确的 javascript:
add = function(dict, vector, k)
{
var size=len(vector);
vector[size]=k;
dict[k]=size;
}
swap(dict, vector, name, newOrder)
{
var oldOrder = dict[name]
if(oldOrder < newOrder)
{
for(var i=oldOrder+1; i<=newOrder; i++)
{ dict[vector[i]]--;
vector[i-1]=vector[i];
}
dict[name]=newOrder;
vector[newOrder]=dict[name]
}
else
{
for(var i=oldOrder-1; i>=newOrder; i--)
{ dict[vector[i]]++;
vector[i+1]=vector[i];
}
dict[name]=newOrder;
vector[newOrder]=dict[name]
}
}
解释:
add = function(dict, vector, k)
{
var size=len(vector);
vector[size]=k;
dict[k]=size;
}
// vector: 0a 1b 2c 3d 4e
// map: a0 b1 c2 d3 e4
swap(dict, vector, name, newOrder)
{
// newOrder = 4
var oldOrder = dict[name]
// oldOrder = 1
if(oldOrder < newOrder)
{
// goes here
for(var i=oldOrder+1; i<=newOrder; i++)
{
// map: a0 b1 c2 d3 e4
dict[vector[i]]--;
// map: a0 b1 c1 d3 e4 //after one iteration
// vector: 0a 1b 2c 3d 4e
vector[i-1]=vector[i];
// vector: 0a 1c 2c 3d 4e //after one iteration
}
// map: a0 b1 c1 d2 e3
// vector: 0a 1c 2d 3e 4e
dict[name]=newOrder;
vector[newOrder]=dict[name]
// map: a0 b4 c1 d2 e3
// vector: 0a 1c 2d 3e 4b
}
else
{
for(var i=oldOrder-1; i>=newOrder; i--)
{ dict[vector[i]]++;
vector[i+1]=vector[i];
}
dict[name]=newOrder;
vector[newOrder]=dict[name]
}
}