【问题标题】:Find the number of remove-then-append operations needed to sort a given array查找对给定数组进行排序所需的先删除后追加操作数
【发布时间】:2012-11-25 07:10:54
【问题描述】:

这是一道面试题。 swap 表示从数组中删除任何元素并将其附加到同一数组的后面。给定一个整数数组,找出对数组进行排序所需的最小swaps 个数。

有没有比O(n^2)更好的解决方案?

例如:

输入数组:[3124]。

swaps的数量:2([3124] -> [1243] -> [1234])。

【问题讨论】:

  • 你检查过这个discussion的内容吗?
  • @bonCodigo:这是一个完全不同(如果相似)的问题。
  • @bonCodigo - 很棒的链接!

标签: arrays algorithm sorting language-agnostic


【解决方案1】:

问题归结为找到作为子序列出现在输入数组中的排序数组的最长前缀。这决定了不需要需要排序的元素。剩下的元素需要从小到大一一删除,在后面追加。

在您的示例[3, 1, 2, 4] 中,已排序的子序列是[1, 2]。最佳解决方案是删除剩余的两个元素3和4,并将它们附加在后面。因此,最佳解决方案是两次“交换”。

使用O(n) 额外内存可以在O(n logn) 时间内找到子序列。下面的伪代码会做到这一点(代码也恰好是有效的 Python):

l = [1, 2, 4, 3, 99, 98, 7]
s = sorted(l)
si = 0
for item in l:
  if item == s[si]:
    si += 1
print len(l) - si

如果如您的示例所示,数组包含从1 到n 的整数排列,则可以使用O(1) 内存在O(n) 时间内解决问题:

l = [1, 2, 3, 5, 4, 6]
s = 1
for item in l:
  if item == s:
    s += 1
print len(l) - s + 1

更一般地说,只要我们先验地知道输出数组,就可以使用第二种方法,因此不需要通过排序找到它。

【讨论】:

  • @NPE 我认为您需要返回 print len(l) - (si+1) 。对吗?
【解决方案2】:

这可能适用于O(nlogn),即使我们不假设数组是连续值。
如果我们这样做 - 它可以在O(n) 中完成。 一种方法是使用O(n) 空间和O(nlogn) 时间。
给定数组 A 将其 (O(nlogn)) 排序到第二个数组 B。
现在...(数组从 1 开始索引)

swaps = 0
b = 1
for a = 1 to len(A)
  if A[a] == B[b]
    b = b + 1
  else
    swaps = swaps + 1

【讨论】:

  • 谢谢。看起来我们可以在 O(n) 中做到这一点。
  • @Michael 即使是非连续元素?
  • 坦率地说,我不懂这个算法。
  • 我会尝试添加一个解释(怎么知道,也许我都错了)
  • 添加了一个可能更容易理解的简短版本。
【解决方案3】:

观察:如果一个元素被交换到后面,它之前的位置无关紧要。没有元素需要多次交换。

观察:最后的交换(如果有的话)必须移动最大的元素。

观察:在交换之前,数组(不包括最后一个元素)必须排序(按以前的交换,或最初)

排序算法,假设值是连续的:找到从 1 开始的连续(按值)元素的最长排序子序列:

3 1 5 2 4

依次交换所有更高的元素:

1 5 2 4 3

1 5 2 3 4

1 2 3 4 5

要在 O(n) 中找到交换次数,求从 1 开始的连续元素的最长排序子序列的长度:

  • 预期 = 1
  • 对于序列中的每个元素
    • 如果元素 == 预期
      • 预计 += 1
  • 返回预期-1

那么交换的数量 = 输入的长度 - 它的最长排序子序列。

另一种解决方案 ( O(n^2) ) 如果输入不是 1..n 的排列:

  • 交换 = 0
  • 循环
    • 查找最大元素的第一个实例并检测数组是否已排序
    • 如果数组已排序,则返回交换。
    • 否则从数组中删除找到的元素并增加交换。

另一种解决方案( O(n log n) ),假设元素独特:

  • 用 {oldPos, newPos, value} 包装每个元素
  • 制作数组的浅拷贝
  • 按值对数组进行排序
  • 存储每个元素的新位置
  • 对(未排序的)副本中的 newPos' 运行排列算法

如果您不想复制输入数组,请改为在最后一步之前按 oldPos 排序。

【讨论】:

    【解决方案4】:

    这可以在 O(n log n) 内完成。

    首先找到数组中的最小元素。现在,找到出现在该元素之前的最大元素。打电话给max_left。您必须为数组的 min 元素之前的所有元素调用 swap()。

    现在,找到最小元素右侧的最长递增子序列,以及应该跳过值大于 max_left 的元素的约束。 所需的交换次数为size(array) - size(LIS)。

    例如考虑数组,

    7 8 9 1 2 5 11 18

    数组中的最小元素是1。所以我们在最小元素之前找到最大值。

    7 8 9 | 1 2 5 11 18

    max_left = 9

    现在,找到元素

    交换次数 = 8 - 3 = 5

    如果max元素为null,即min是第一个元素,求数组的LIS,需要的答案是size(array)-size(LIS)

    举例

    2 5 4 3

    max_left 为空。 LIS 是2 3

    交换次数 = size(array) - size(LIS) = 4 - 2 = 2

    【讨论】:

    • 所需的交换数 = 最小值左侧的元素数 + 右侧所需的交换数。交换次数取决于右侧的 LIS。只有最大递增子序列中的元素(条件是它们小于左侧最大值的值)保持不变,而其他元素需要交换才能对数组进行排序。基本上,排序过程涉及将元素交换到 min 的左侧,而左侧的大于 max 的元素需要在交换右侧的元素后交换到前面。
    • @nkskalyan,2、5、4、3 怎么样。最小元素 = 2,最小值之前的最大值 = 无,LIS = 1,根据您的逻辑回答 = 4-1 = 3,但正确答案是 1。
    • @DeveshAgrawal 很好,当我第一次编写这段代码时没有考虑基本情况。如果maxBeforeMin = null,我认为可以通过在没有任何约束的情况下找到LIS来完成。在 2,5,4,3 的情况下,LIS->(2,5) No of swaps= 4-2 = 2 正确答案是 2,因为您需要同时交换 5 和 4。如果我错过了,请告诉我一些东西,否则将编辑上述算法以包含这种情况
    • 请定义 LIS 是什么?
    【解决方案5】:

    这是python中最小交换次数的代码,

    def find_cycles(array):
       cycles = []
       remaining = set(array)
       while remaining:
          j = i = remaining.pop()
          cycle = [i]
          while True:
             j = array[j]
             if j == i:
                 break
             array.append(j)
             remaining.remove(j)
          cycles.append(cycle)
       return cycles
    
    def minimum_swaps(seq):
        return sum(len(cycle) - 1 for cycle in find_cycles(seq))
    

    【讨论】:

      【解决方案6】:

      O(1) 空间和 O(N) (~ 2*N) 解决方案 假设 min 元素为 1,并且数组包含从 1 到 N-1 的所有数字,没有任何重复值。其中 N 是数组长度。

      int minimumSwaps(int[] a) {
          int swaps = 0;
          int i = 0;
          while(i < a.length) {
              int position = a[i] - 1;
              if(position != i) {
                  int temp = a[position];
                  a[position] = a[i];
                  a[i] = temp;
                  swaps++;
              } else {
                  i++;
              }
          }
          return swaps;
      }
      

      【讨论】:

        【解决方案7】:
        int numSwaps(int arr[], int length) {
        bool sorted = false; 
        int swaps = 0;
        while(!sorted) {
            int inversions = 0;
            int t1pos,t2pos,t3pos,t4pos = 0;
            for (int i =  1;i < length; ++i)
            {
                if(arr[i] < arr[i-1]){
                    if(inversions){
                        tie(t3pos,t4pos) = make_tuple(i-1, i);
                    }
                    else tie(t1pos, t2pos) = make_tuple(i-1, i);
                    inversions++;
                }
                if(inversions == 2)
                    break;
            }
            if(!inversions){
                sorted = true;
            }
            else if(inversions == 1) {
                swaps++; 
                int temp = arr[t2pos];
                arr[t2pos] = arr[t1pos];
                arr[t1pos] = temp;
            }
            else{
                swaps++;
                if(arr[t4pos] < arr[t2pos]){
                    int temp = arr[t1pos];
                    arr[t1pos] = arr[t4pos];
                    arr[t4pos] = temp;
                }
                else{
                    int temp = arr[t2pos];
                    arr[t2pos] = arr[t1pos];
                    arr[t1pos] = temp;
                }
            }
        }
        return swaps;
        }
        

        此代码返回对数组就地排序所需的最小交换次数。

        例如,A[] = [7,3,4,1] 通过交换 1 和 7,我们得到 [1,3,4,7]。 类似地 B[] = [1,2,6,4,8,7,9]。我们首先将 6 与 4 交换,因此,B[] -> [1,2,4,6,8,7,9]。然后是 7 和 8。所以 -> [1,2,4,6,7,8,9]

        算法以 O(索引 i 处的值

        【讨论】:

          【解决方案8】:

          编写一个非常简单的 JavaScript 程序来对数组进行排序并找到交换次数:

            function findSwaps(){
          
              let arr = [4, 3, 1, 2];
              let swap = 0
              var n = arr.length
              for (let i = 0; i < n; i++) {
                  for (let j = i + 1; j < n; j++) {
                      if (arr[i] > arr[j]) {
                          arr[i] = arr[i] + arr[j];
                          arr[j] = arr[i] - arr[j];
                          arr[i] = arr[i] - arr[j]
                          swap = swap + 1
                      }
                  }
              }
              console.log(arr);
              console.log(swap)
            }
          

          【讨论】:

          • (让 i = 0; i
          • @NabinKumarKhatiwada 请立即运行并检查代码。谢谢
          • 我已经使用冒泡排序解决了这个问题,您的解决方案有点类似于冒泡排序。冒泡排序仍然比您的解决方案好。这个 hack 等级问题不会接受冒泡排序,因为这个算法需要很长时间来处理。
          • @NabinKumarKhatiwada 是的,我已经解决了。我怎么能帮助你呢?给我这个问题的stackoverflow链接,我会在那里发布解决方案。
          • 我跑了,结果是 5 而不是 3
          【解决方案9】:
          for(int count = 1; count<=length; count++)
          {
              tempSwap=0; //it will count swaps per iteration
              for(int i=0; i<length-1; i++)
                  if(a[i]>a[i+1])
                  {
                     swap(a[i],a[i+1]);
                     tempSwap++;
                  }
              if(tempSwap!=0) //check if array is already sorted!
                  swap += tempSwap;
              else
                  break;
          }
          System.out.println(swaps);
          

          【讨论】:

          • 嗨,欢迎来到 Stack Overflow。由于这是一个古老的问题,有很多流行的答案,包括一个已接受的答案,请编辑您的答案以解释它提供的现有答案所没有的内容。谢谢。
          • 你能解释一下为什么你有变量名交换和函数交换。搞糊涂了。如果您能解释一下,将会很有帮助。
          【解决方案10】:

          这是一个适用于所有输入的 O(n) 解决方案:

          static int minimumSwaps(int[] arr) {
                  int swap=0;
                  boolean visited[]=new boolean[arr.length];
          
                  for(int i=0;i<arr.length;i++){
                      int j=i,cycle=0;
          
                      while(!visited[j]){
                          visited[j]=true;
                          j=arr[j]-1;
                          cycle++;
                      }
          
                      if(cycle!=0)
                          swap+=cycle-1;
                  }
                  return swap;
              }
          }
          

          【讨论】:

          • 您的解决方案是否适用于 {3,2,1}?此外,当数组的值远大于 arr.length 时,它似乎不起作用。
          • @agugglez 是的,它确实适用于 {3,2,1},您可以对其进行测试。是的,正如您正确指出的那样,它仅适用于每个元素值应小于或等于数组大小的连续元素数组。
          • 你确定吗?您认为输入 {3,2, 1} 的正确答案应该是什么?
          【解决方案11】:
          def minimumSwaps(arr):
              swaps = 0
              '''
              first sort the given array to determine the correct indexes 
              of its elements
              '''
              temp = sorted(arr)
          
              # compare unsorted array with the sorted one
              for i in range(len(arr)):
                  '''
                  if ith element in the given array is not at the correct index
                  then swap it with the correct index, since we know the correct
                  index because of sorting. 
                  '''
                  if arr[i] != temp[i]: 
                    swaps += 1
                    a = arr[i]
                    arr[arr.index(temp[i])] = a
                    arr[i] = temp[i]    
              return swaps
          

          【讨论】:

          • 请添加一些描述。
          • @Nikolas 我添加了描述
          【解决方案12】:

          如果你注意到数组中的一个元素需要被删除和附加,我认为这个问题可以在 O(N) 内解决:

          • 右侧有一个较小的元素,或者...
          • 他的左侧有一个较小的元素需要移除和附加。

          然后它只是识别需要删除和附加的元素。代码如下:

          static int minMoves(int arr[], int n) {
              if (arr.length == 0) return 0;
          
              boolean[] willBeMoved = new boolean[n]; // keep track of elements to be removed and appended
              int min = arr[n - 1]; // keep track of the minimum
          
              for (int i = n - 1; i >= 0; i--) { // traverse the array from the right
                  if (arr[i] < min) min = arr[i]; // found a new min
                  else if (arr[i] > min) { // arr[i] has a smaller element to the right, so it will need to be moved at some point
                      willBeMoved[i] = true;
                  }
              }
          
              int minToBeMoved = -1; // keep track of the minimum element to be removed and appended
              int result = 0; // the answer
          
              for (int i = 0; i < n; i++) { // traverse the array from the left
                  if (minToBeMoved == -1 && !willBeMoved[i]) continue; // find the first element to be moved
                  if (minToBeMoved == -1) minToBeMoved = i;
          
                  if (arr[i] > arr[minToBeMoved]) { // because a smaller value will be moved to the end, arr[i] will also have to be moved at some point
                      willBeMoved[i] = true;
                  } else if (arr[i] < arr[minToBeMoved] && willBeMoved[i]) { // keep track of the min value to be moved
                      minToBeMoved = i;
                  }
          
                  if (willBeMoved[i]) result++; // increment
              }
          
              return result;
          }
          

          它使用 O(N) 空间。

          【讨论】:

            【解决方案13】:

            @all ,@Itay karo 和 @NPE 提供的公认解决方案是完全错误的,因为它没有考虑未来交换元素的顺序...

            对于许多测试用例,它失败,例如:

            3 1 2 5 4

            正确输出:4

            但他们的代码输出为 3...

            解释:3 1 2 5 4--->1 2 5 4 3--->1 2 4 3 5--->1 2 3 5 4--->1 2 3 4 5

            PS:由于声誉低,我无法在那里发表评论

            【讨论】:

            • 你错了。在您的测试用例中,正确的结果是 3:3 1 2 5 4 ---&gt; 1 2 5 4 3---&gt; 1 2 5 3 4 ---&gt; 1 2 3 4 5。仔细阅读@NPE 回答:剩下的元素需要一个一个删除,从小到大,在后面追加。
            【解决方案14】:

            听听是我在 c# 中的解决方案,用于解决缩短数组所需的最小交换次数 有时我们只能交换 2 个元素(在任何索引位置)。

            public class MinimumSwaps2
            {
                public static void minimumSwapsMain(int[] arr)
                {
            
                    Dictionary<int, int> dic = new Dictionary<int, int>();
                    Dictionary<int, int> reverseDIc = new Dictionary<int, int>();
                    int temp = 0;
                    int indx = 0;
              //find the maximum number from the array
                    int maxno = FindMaxNo(arr);
            
                    if (maxno == arr.Length)
                    {
                        for (int i = 1; i <= arr.Length; i++)
                        {
                            dic[i] = arr[indx];
                            reverseDIc.Add(arr[indx], i);
                            indx++;
                        }
                    }
                    else
                    {
                        for (int i = 1; i <= arr.Length; i++)
                        {
                            if (arr.Contains(i))
                            {
                                dic[i] = arr[indx];
                                reverseDIc.Add(arr[indx], i);
                                indx++;
                            }
            
                        }
                    }
            
                    int counter = FindMinSwaps(dic, reverseDIc, maxno);
            
            
                }
                static int FindMaxNo(int[] arr)
                {
                    int maxNO = 0;
                    for (int i = 0; i < arr.Length; i++)
                    {
                        if (maxNO < arr[i])
                        {
                            maxNO = arr[i];
                        }
                    }
                    return maxNO;
                }
                static int FindMinSwaps(Dictionary<int, int> dic, Dictionary<int, int> reverseDIc, int maxno)
                {
                    int counter = 0;
                    int temp = 0;
                    for (int i = 1; i <= maxno; i++)
                    {
                        if (dic.ContainsKey(i))
                        {
                            if (dic[i] != i)
                            {
                                counter++;
                                var myKey1 = reverseDIc[i];
                                temp = dic[i];
                                dic[i] = dic[myKey1];
                                dic[myKey1] = temp;
            
                                reverseDIc[temp] = reverseDIc[i];
                                reverseDIc[i] = i;
                            }
                        }
                    }
                    return counter;
                }
            }
            

            【讨论】:

            • 这个问题只允许“交换”到数组的末尾。
            【解决方案15】:
            int temp = 0, swaps = 0;
                    for (int i = 0; i < arr.length;) {
                        if (arr[i] != i + 1){ 
                        //  System.out.println("Swapping --"+arr[arr[i] - 1] +"  AND -- "+arr[i]);
                            temp = arr[arr[i] - 1];
                            arr[arr[i] - 1] = arr[i];
                            arr[i] = temp;
                            ++swaps;
                        } else
                            ++i;
                            //  System.out.println("value at position -- "+ i +" is set to -- "+ arr[i]);
                    }
                    return swaps;
            

            这是我找到的最优化的答案。就是这么简单。您可能会通过循环一看就明白。感谢黑客级别的 Darryl。

            【讨论】:

            • 在 Hacker Rank 中哪里可以找到这个问题?
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-08-11
            • 1970-01-01
            • 2015-10-22
            • 2020-05-02
            • 2022-01-14
            • 2011-02-18
            • 2020-12-27
            相关资源
            最近更新 更多