本文简单介绍了几种计算逆序数的实现方法
所谓逆序数,是指一个排列中所有逆序对的总数,而所谓逆序对,则是指排列中前后位置和大小顺序相反的数对,举个简单的例子:
\{\ 1, 4, 2, 3 \ \}
上面的排列中,有下面两个逆序对:
<4, 2>\ <4, 3>
所以该排列的逆序数为 2
function inverse_number(seq)
local inv_num = 0
for i = 1, #seq - 1 do
for j = i + 1, #seq do
if seq[i] > seq[j] then
inv_num = inv_num + 1
end
end
end
return inv_num
end
-- assume seq contains "1, 2, 3, 4" only
function inverse_number(seq)
local inv_num = 0
local count_buffer = { 0, 0, 0, 0 }
for i = 1, #seq do
if seq[i] == 1 then
inv_num = inv_num + count_buffer[2] + count_buffer[3] + count_buffer[4]
count_buffer[1] = count_buffer[1] + 1
elseif seq[i] == 2 then
inv_num = inv_num + count_buffer[3] + count_buffer[4]
count_buffer[2] = count_buffer[2] + 1
elseif seq[i] == 3 then
inv_num = inv_num + count_buffer[4]
count_buffer[3] = count_buffer[3] + 1
else
count_buffer[4] = count_buffer[4] + 1
end
end
return inv_num
end
function inverse_number(seq)
local inv_num = 0
local count_buffer = {}
for i = 1, #seq do
for k, v in pairs(count_buffer) do
if k > seq[i] then
inv_num = inv_num + v
end
end
count_buffer[seq[i]] = (count_buffer[seq[i]] or 0) + 1
end
return inv_num
end