這是一個解決方案,不會遍歷地圖中的所有元素。
這只是複雜的,我不認爲它提高了小數據集的速度。
抱歉,這是不恰當的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]
}
}
所以如果你有'k'項,那麼你就只能從有值'0'到'K-1'? – titus
是的。最好。無論如何,我可以通過索引對結構進行排序,然後遍歷它並將i ++作爲一個位置,以使1,2,5變爲0,1,2(例如)。但是如果這可以在第一次(也是唯一)的迭代中完成,那會更好。 – DEgorov
'k'的數量級是多少?需要多久調用一次該函數? – titus