![](/img/trans.png)
[英]Count the number of inversions in an array that is sorted in increasing order then decreasing order
[英]How to add specific number of inversions to sorted array
給定一個排序數組,有沒有辦法在特定位置插入特定數量的反轉? 起初我以為這很簡單,但是后來意識到反轉可以彼此“撤消”。 考慮:
以數組開頭:2,4,6,8
一反轉:4,2,6,8
現在,如果您想添加另一個反演(隨機地),您可能會得到4,2,8,6,這會很好,或者您可能會得到2,4,6,8,這會很糟糕,因為它會返回原本的。
使用完索引后,刪除索引也不起作用。 例如1,2,3-> 3,2,1,如果我們排除了第一個索引和最后一個索引,則會錯過3,1,2的排列,因此這種方法行不通。
它不必是數組。 它可以是列表或其他結構。
關於算法有什么建議嗎?
Number of inversions in an array is -
For a given array a[n]
An inversion is -
if a[i] > a[j] such that i<j
Also,
Max number of inversions = n*(n-1)/2
where n is the size of array
Now use this algorithm , Inversion with count k
0. Sort the array in ascending order
1. Find greatest l, such that l(l-1)/2 < k
2. Take first l smallest numbers and arrange in descending order.
3. Compute m = k - l(l-1)/2
4. Place the (l+1)th smallest number and place it at (l-m + 1)th
position, shifting others by one place to the right.
Example :
arr = [1,2,3,4,5]
Inversion = 8
l = 4 , as 4*3/2 = 6
m = 8 - 6 = 2
So,
0. Sorting the array => [1,2,3,4,5]
1. l = 4
2. 4 3 2 1 5
3. m = 2
4. Placing 5 at 3rd position, by shifting others one place to right => 4 3 5 2 1
Hence your answer become 4 3 5 2 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.