Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何向排序数组添加特定数量的反转_Arrays_Algorithm_Sorting_Language Agnostic_Permutation - Fatal编程技术网

Arrays 如何向排序数组添加特定数量的反转

Arrays 如何向排序数组添加特定数量的反转,arrays,algorithm,sorting,language-agnostic,permutation,Arrays,Algorithm,Sorting,Language Agnostic,Permutation,给定一个排序数组,是否有方法插入特定数量的反转(在随机位置)?起初我认为这很简单,但后来意识到反转可以相互“撤销”。考虑: 从数组开始: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,所以这种方法不起作用 它不必是数组。它可以是一个列

给定一个排序数组,是否有方法插入特定数量的反转(在随机位置)?起初我认为这很简单,但后来意识到反转可以相互“撤销”。考虑:

从数组开始: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
对于给定数组a[n] 反转是- 如果a[i]>a[j]使得i[1,2,3,4,5] 1.l=4 2.4 3 2 1 5 3.m=2 4.将5位置于第3位,将其他位置向右移动一位=>4 3 5 2 1 因此,你的答案变成4 3 5 2 1
“现在,如果你想添加另一个反转(随机),你可以得到4,2,6,8,这很好”,这将添加0个反转,不是吗?为什么这会被认为是好的?@AmiTavory谢谢你所说的“添加”是什么意思,你是指一次交换一对整数?@shole我不明白你的意思?@Celeritas我不明白随机插入反转是什么意思?我可以在列表中插入一个新的整数来实现目标吗?就像{2,4,6,8}-->{2,4,6,9,8}=+1反转…但是从你的例子来看,似乎只允许交换一对现有的整数?你从哪里得到的?简单的逻辑。反转是移位位置数的计数。如前所述:如果a[i]>a[j],则反转是指i不满足“仅交换1对数字”的条件……或者需要满足吗?