📌  相关文章
📜  重新排列一个数组,使得 arr[i] = i

📅  最后修改于: 2021-10-27 07:43:28             🧑  作者: Mango

给定一个长度为 N 的元素数组,范围从 0 到 N – 1。数组中可能不存在所有元素。如果该元素不存在,则数组中将存在 -1。重新排列数组,使 A[i] = i,如果 i 不存在,则在该位置显示 -1。

例子:

Input : arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1}
Output : [-1, 1, 2, 3, 4, -1, 6, -1, -1, 9]

Input : arr = {19, 7, 0, 3, 18, 15, 12, 6, 1, 8,
              11, 10, 9, 5, 13, 16, 2, 14, 17, 4}
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
         11, 12, 13, 14, 15, 16, 17, 18, 19]

方法(朴素方法):

  1. 导航数字从 0 到 n-1。
  2. 现在浏览数组。
  3. 如果 (i==a[j]) ,则将 i 位置的元素替换为 a[j] 位置。
  4. 如果有任何元素使用 -1 而不是数字,那么它将被自动替换。
  5. 现在,遍历数组并检查是否 (a[i]!=i) ,如果为真,则将 a[i] 替换为 -1。

下面是上述方法的实现:

C++
// C++ program for above approach
#include 
using namespace std;
 
// Function to transform the array
void fixArray(int ar[], int n)
{
    int i, j, temp;
 
    // Iterate over the array
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
        {
            // Check is any ar[j]
            // exists such that
            // ar[j] is equal to i
            if (ar[j] == i) {
                temp = ar[j];
                ar[j] = ar[i];
                ar[i] = temp;
                break;
            }
        }
    }
 
    // Iterate over array
    for (i = 0; i < n; i++)
    {
        // If not present
        if (ar[i] != i)
        {
            ar[i] = -1;
        }
    }
 
    // Print the output
    cout << "Array after Rearranging" << endl;
    for (i = 0; i < n; i++) {
        cout << ar[i] << " ";
    }
}
 
// Driver Code
int main()
{
    int n, ar[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
    n = sizeof(ar) / sizeof(ar[0]);
 
    // Function Call
    fixArray(ar, n);
}
 
// Code BY Tanmay Anand


Java
// Java program for above approach
class GFG{
     
// Function to transform the array
public static void fixArray(int ar[], int n)
{
    int i, j, temp;
     
    // Iterate over the array
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < n; j++)
        {
             
            // Check is any ar[j]
            // exists such that
            // ar[j] is equal to i
            if (ar[j] == i)
            {
                temp = ar[j];
                ar[j] = ar[i];
                ar[i] = temp;
                break;
            }
        }
    }
  
    // Iterate over array
    for(i = 0; i < n; i++)
    {
         
        // If not present
        if (ar[i] != i)
        {
            ar[i] = -1;
        }
    }
  
    // Print the output
    System.out.println("Array after Rearranging");
    for(i = 0; i < n; i++)
    {
        System.out.print(ar[i] + " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int n, ar[] = { -1, -1, 6, 1, 9,
                     3, 2, -1, 4, -1 };
    n = ar.length;
  
    // Function Call
    fixArray(ar, n);
}
}
 
// This code is contributed by divyesh072019


Python3
# Python3 program for above approach
 
# Function to transform the array
def fixArray(ar, n):
     
    # Iterate over the array
    for i in range(n):
        for j in range(n):
 
            # Check is any ar[j]
            # exists such that
            # ar[j] is equal to i
            if (ar[j] == i):
                ar[j], ar[i] = ar[i], ar[j]
 
    # Iterate over array
    for i in range(n):
         
        # If not present
        if (ar[i] != i):
            ar[i] = -1
 
    # Print the output
    print("Array after Rearranging")
 
    for i in range(n):
        print(ar[i], end = " ")
 
# Driver Code
ar = [ -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 ]
n = len(ar)
 
# Function Call
fixArray(ar, n);
 
# This code is contributed by rag2127


C#
// C# program for above approach
using System;
class GFG {
     
    // Function to transform the array
    static void fixArray(int[] ar, int n)
    {
        int i, j, temp;
          
        // Iterate over the array
        for(i = 0; i < n; i++)
        {
            for(j = 0; j < n; j++)
            {
                  
                // Check is any ar[j]
                // exists such that
                // ar[j] is equal to i
                if (ar[j] == i)
                {
                    temp = ar[j];
                    ar[j] = ar[i];
                    ar[i] = temp;
                    break;
                }
            }
        }
       
        // Iterate over array
        for(i = 0; i < n; i++)
        {
              
            // If not present
            if (ar[i] != i)
            {
                ar[i] = -1;
            }
        }
       
        // Print the output
        Console.WriteLine("Array after Rearranging");
        for(i = 0; i < n; i++)
        {
            Console.Write(ar[i] + " ");
        }
    } 
     
  static void Main() {
        int[] ar = { -1, -1, 6, 1, 9,
                     3, 2, -1, 4, -1 };
        int n = ar.Length;
       
        // Function Call
        fixArray(ar, n);
  }
}
 
// This code is contributed by divyeshrabadiya07


Javascript


C++
// C++ program for rearrange an
// array such that arr[i] = i.
#include 
 
using namespace std;
 
// Function to rearrange an array
// such that arr[i] = i.
void fixArray(int A[], int len)
{
    for (int i = 0; i < len; i++)
    {
        if (A[i] != -1 && A[i] != i)
        {
            int x = A[i];
 
            // check if desired place
            // is not vacate
            while (A[x] != -1 && A[x] != x)
            {
                // store the value from
                // desired place
                int y = A[x];
 
                // place the x to its correct
                // position
                A[x] = x;
 
                // now y will become x, now
                // search the place for x
                x = y;
            }
 
            // place the x to its correct
            // position
            A[x] = x;
 
            // check if while loop hasn't
            // set the correct value at A[i]
            if (A[i] != i)
            {
                // if not then put -1 at
                // the vacated place
                A[i] = -1;
            }
        }
    }
}
 
// Driver code
int main()
{
    int A[] = { -1, -1, 6, 1, 9,
               3, 2, -1, 4, -1 };
 
    int len = sizeof(A) / sizeof(A[0]);
 
    // Function Call
    fixArray(A, len);
 
    // Print the output
    for (int i = 0; i < len; i++)
        cout << A[i] << " ";
}
 
// This code is contributed by Smitha Dinesh Semwal


Java
// Java program for rearrange an
// array such that arr[i] = i.
import java.util.*;
import java.lang.*;
 
public class GfG {
 
    // Function to rearrange an array
    // such that arr[i] = i.
    public static int[] fix(int[] A)
    {
        for (int i = 0; i < A.length; i++)
        {
            if (A[i] != -1 && A[i] != i)
            {
                int x = A[i];
 
                // check if desired place
                // is not vacate
                while (A[x] != -1 && A[x] != x)
                {
                    // store the value from
                    // desired place
                    int y = A[x];
 
                    // place the x to its correct
                    // position
                    A[x] = x;
 
                    // now y will become x, now
                    // search the place for x
                    x = y;
                }
 
                // place the x to its correct
                // position
                A[x] = x;
 
                // check if while loop hasn't
                // set the correct value at A[i]
                if (A[i] != i)
                {
                    // if not then put -1 at
                    // the vacated place
                    A[i] = -1;
                }
            }
        }
        return A;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int A[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
        System.out.println(Arrays.toString(fix(A)));
    }
}


Python3
# Python3 program for rearrange an
# array such that arr[i] = i.
 
# Function to rearrange an array
# such that arr[i] = i.
 
 
def fix(A, len):
 
    for i in range(0, len):
 
        if (A[i] != -1 and A[i] != i):
            x = A[i]
 
            # check if desired place
            # is not vacate
            while (A[x] != -1 and A[x] != x):
                 
                # store the value from
                # desired place
                y = A[x]
 
                # place the x to its correct
                # position
                A[x] = x
 
                # now y will become x, now
                # search the place for x
                x = y
 
            # place the x to its correct
            # position
            A[x] = x
 
            # check if while loop hasn't
            # set the correct value at A[i]
            if (A[i] != i):
 
                # if not then put -1 at
                # the vacated place
                A[i] = -1
 
 
# Driver code
A = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
 
fix(A, len(A))
 
for i in range(0, len(A)):
    print(A[i], end=' ')
 
# This code is contributed by Saloni1297


C#
// C# program for rearrange
// an array such that
// arr[i] = i.
using System;
 
class GfG {
    // Function to rearrange an
    // array such that arr[i] = i.
    public static int[] fix(int[] A)
    {
        for (int i = 0; i < A.Length; i++)
        {
            if (A[i] != -1 && A[i] != i)
            {
                int x = A[i];
 
                // check if desired
                // place is not vacate
                while (A[x] != -1 && A[x] != x)
                {
                    // store the value
                    // from desired place
                    int y = A[x];
 
                    // place the x to its
                    // correct position
                    A[x] = x;
 
                    // now y will become x,
                    // now search the place
                    // for x
                    x = y;
                }
 
                // place the x to its
                // correct position
                A[x] = x;
 
                // check if while loop
                // hasn't set the correct
                // value at A[i]
                if (A[i] != i)
                {
                    // if not then put -1
                    // at the vacated place
                    A[i] = -1;
                }
            }
        }
        return A;
    }
 
    // Driver Code
    static void Main()
    {
        int[] A = new int[] { -1, -1, 6,  1, 9,
                              3,  2,  -1, 4, -1 };
        Console.WriteLine(string.Join(",", fix(A)));
    }
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)


PHP


Javascript


C++
#include 
#include 
 
using namespace std;
 
//
void fixArray(int arr[], int n)
{
  // Initialize a hashmap
  std::unordered_map hmap;
   
  // Enter each element in hmap
  for(int i{0}; i


Java
// Java program for rearrange an
// array such that arr[i] = i.
import java.util.*;
import java.lang.*;
 
class GfG {
 
    // Function to rearrange an array
    // such that arr[i] = i.
    public static int[] fix(int[] A)
    {
        Set s = new HashSet();
 
        // Storing all the values in the HashSet
        for(int i = 0; i < A.length; i++)
        {
           s.add(A[i]);
        }
 
        for(int i = 0; i < A.length; i++)
        {
           if(s.contains(i))
             A[i] = i;
           else
             A[i] = -1;
        }
 
      return A;
}
 
    // Driver code
    public static void main(String[] args)
    {
        int A[] = {-1, -1, 6, 1, 9,
                    3, 2, -1, 4,-1};
                     
        // Function calling
        System.out.println(Arrays.toString(fix(A)));
    }
}


Python3
# Python3 program for rearrange an
# array such that arr[i] = i.
 
# Function to rearrange an array
# such that arr[i] = i.
def fix(A):
    s = set()
     
    # Storing all the values in the Set
    for i in range(len(A)):
        s.add(A[i])
 
    for i in range(len(A)):
       
        # check for item if present in set
        if i in s:
            A[i] = i
        else:
            A[i] = -1
    return A
     
# Driver code
if __name__ == "__main__":
    A = [-1, -1, 6, 1, 9,
          3, 2, -1, 4,-1]
    print(fix(A))
 
# This code is contributed by Chitranayal


C#
using System;
using System.Collections.Generic;
public class main{
    static void fix(int[] a,int n){
       HashSet hs=new HashSet();
         
        // Traverse the array
        // and add each element
        // to the HashSet
        for(int i=0;i i=n-1
        for(int i=0;i


Javascript


C++
// C++ program for rearrange an
// array such that arr[i] = i.
#include 
 
void fixArray(int arr[], int n)
{
 
    for (int i = 0; i < n;)
    {
        if (arr[i] >= 0 && arr[i] != i)
            arr[arr[i]] = (arr[arr[i]] + arr[i])
                          - (arr[i] = arr[arr[i]]);
        else
            i++;
    }
}
 
// Driver Code
int main()
{
    int arr[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Fucnction Call
    fixArray(arr, n);
 
    // Print output
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}
 
// This Code is Contributed by Adarsh_Verma


Java
// Java program for rearrange an
// array such that arr[i] = i.
import java.util.Arrays;
 
class Program
{
    public static void main(String[] args)
    {
        int[] arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
        for (int i = 0; i < arr.length;)
        {
            if (arr[i] >= 0 && arr[i] != i)
            {
                int ele = arr[arr[i]];
                arr[arr[i]] = arr[i];
                arr[i] = ele;
            }
            else
            {
                i++;
            }
        }
        System.out.println(Arrays.toString(arr));
    }
}
 
/* This Java code is contributed by PrinciRaj1992*/


Python3
# Python3 program for rearrange an
# array such that arr[i] = i.
if __name__ == "__main__":
 
    arr = [-1, -1, 6, 1, 9,
           3, 2, -1, 4, -1]
    n = len(arr)
    i = 0
    while i < n:
 
        if (arr[i] >= 0 and arr[i] != i):
            (arr[arr[i]],
             arr[i]) = (arr[i],
                        arr[arr[i]])
        else:
            i += 1
 
    for i in range(n):
        print(arr[i], end=" ")
 
# This code is contributed by Chitranayal


C#
// C# program for rearrange an
// array such that arr[i] = i.
using System;
 
namespace GFG {
 
class Program {
    static void Main(string[] args)
    {
        int[] arr = { -1, -1, 6, 1, 9,
                     3, 2, -1, 4, -1 };
        for (int i = 0; i < arr.Length;)
        {
            if (arr[i] >= 0 && arr[i] != i)
            {
                int ele = arr[arr[i]];
                arr[arr[i]] = arr[i];
                arr[i] = ele;
            }
            else
            {
                i++;
            }
        }
        Console.WriteLine(String.Join(",", arr));
    }
}
}
// This code is contributed by
// Venkata VardhiReddy(venkata)


Javascript


输出

Array after Rearranging
-1 1 2 3 4 -1 6 -1 -1 9

时间复杂度: O(n 2 )

另一种方法:
1. 浏览阵列。
2. 检查是否 a[i] = -1,如果是则忽略它。
3. 如果 a[i] != -1,检查元素 a[i] 是否在其正确位置 (i=A[i]) 。如果是,则忽略它。
4. 如果 a[i] != -1 并且元素 a[i] 不在其正确位置 (i!=A[i])则将其放置在其正确位置,但有两个条件:

  • 要么A[i] 是 vacate ,意味着A[i] = -1 ,然后只是把A[i] = i
  • OR A[i] 不是 vacate ,意味着A[i] = x ,然后int y=x put A[i] = i 。现在,我们需要将y放置到正确的位置,因此从步骤 3 开始重复。

下面是上述方法的实现:

C++

// C++ program for rearrange an
// array such that arr[i] = i.
#include 
 
using namespace std;
 
// Function to rearrange an array
// such that arr[i] = i.
void fixArray(int A[], int len)
{
    for (int i = 0; i < len; i++)
    {
        if (A[i] != -1 && A[i] != i)
        {
            int x = A[i];
 
            // check if desired place
            // is not vacate
            while (A[x] != -1 && A[x] != x)
            {
                // store the value from
                // desired place
                int y = A[x];
 
                // place the x to its correct
                // position
                A[x] = x;
 
                // now y will become x, now
                // search the place for x
                x = y;
            }
 
            // place the x to its correct
            // position
            A[x] = x;
 
            // check if while loop hasn't
            // set the correct value at A[i]
            if (A[i] != i)
            {
                // if not then put -1 at
                // the vacated place
                A[i] = -1;
            }
        }
    }
}
 
// Driver code
int main()
{
    int A[] = { -1, -1, 6, 1, 9,
               3, 2, -1, 4, -1 };
 
    int len = sizeof(A) / sizeof(A[0]);
 
    // Function Call
    fixArray(A, len);
 
    // Print the output
    for (int i = 0; i < len; i++)
        cout << A[i] << " ";
}
 
// This code is contributed by Smitha Dinesh Semwal

Java

// Java program for rearrange an
// array such that arr[i] = i.
import java.util.*;
import java.lang.*;
 
public class GfG {
 
    // Function to rearrange an array
    // such that arr[i] = i.
    public static int[] fix(int[] A)
    {
        for (int i = 0; i < A.length; i++)
        {
            if (A[i] != -1 && A[i] != i)
            {
                int x = A[i];
 
                // check if desired place
                // is not vacate
                while (A[x] != -1 && A[x] != x)
                {
                    // store the value from
                    // desired place
                    int y = A[x];
 
                    // place the x to its correct
                    // position
                    A[x] = x;
 
                    // now y will become x, now
                    // search the place for x
                    x = y;
                }
 
                // place the x to its correct
                // position
                A[x] = x;
 
                // check if while loop hasn't
                // set the correct value at A[i]
                if (A[i] != i)
                {
                    // if not then put -1 at
                    // the vacated place
                    A[i] = -1;
                }
            }
        }
        return A;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int A[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
        System.out.println(Arrays.toString(fix(A)));
    }
}

蟒蛇3

# Python3 program for rearrange an
# array such that arr[i] = i.
 
# Function to rearrange an array
# such that arr[i] = i.
 
 
def fix(A, len):
 
    for i in range(0, len):
 
        if (A[i] != -1 and A[i] != i):
            x = A[i]
 
            # check if desired place
            # is not vacate
            while (A[x] != -1 and A[x] != x):
                 
                # store the value from
                # desired place
                y = A[x]
 
                # place the x to its correct
                # position
                A[x] = x
 
                # now y will become x, now
                # search the place for x
                x = y
 
            # place the x to its correct
            # position
            A[x] = x
 
            # check if while loop hasn't
            # set the correct value at A[i]
            if (A[i] != i):
 
                # if not then put -1 at
                # the vacated place
                A[i] = -1
 
 
# Driver code
A = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
 
fix(A, len(A))
 
for i in range(0, len(A)):
    print(A[i], end=' ')
 
# This code is contributed by Saloni1297

C#

// C# program for rearrange
// an array such that
// arr[i] = i.
using System;
 
class GfG {
    // Function to rearrange an
    // array such that arr[i] = i.
    public static int[] fix(int[] A)
    {
        for (int i = 0; i < A.Length; i++)
        {
            if (A[i] != -1 && A[i] != i)
            {
                int x = A[i];
 
                // check if desired
                // place is not vacate
                while (A[x] != -1 && A[x] != x)
                {
                    // store the value
                    // from desired place
                    int y = A[x];
 
                    // place the x to its
                    // correct position
                    A[x] = x;
 
                    // now y will become x,
                    // now search the place
                    // for x
                    x = y;
                }
 
                // place the x to its
                // correct position
                A[x] = x;
 
                // check if while loop
                // hasn't set the correct
                // value at A[i]
                if (A[i] != i)
                {
                    // if not then put -1
                    // at the vacated place
                    A[i] = -1;
                }
            }
        }
        return A;
    }
 
    // Driver Code
    static void Main()
    {
        int[] A = new int[] { -1, -1, 6,  1, 9,
                              3,  2,  -1, 4, -1 };
        Console.WriteLine(string.Join(",", fix(A)));
    }
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)

PHP


Javascript


输出
-1 1 2 3 4 -1 6 -1 -1 9

另一种方法(使用 HashSet):
1) 将数组中存在的所有数字存储到一个 HashSet 中
2) 遍历数组的长度,如果HashSet中存在对应的位置元素,则设置A[i] = i,否则A[i] = -1

下面是上述方法的实现。

C++

#include 
#include 
 
using namespace std;
 
//
void fixArray(int arr[], int n)
{
  // Initialize a hashmap
  std::unordered_map hmap;
   
  // Enter each element in hmap
  for(int i{0}; i

Java

// Java program for rearrange an
// array such that arr[i] = i.
import java.util.*;
import java.lang.*;
 
class GfG {
 
    // Function to rearrange an array
    // such that arr[i] = i.
    public static int[] fix(int[] A)
    {
        Set s = new HashSet();
 
        // Storing all the values in the HashSet
        for(int i = 0; i < A.length; i++)
        {
           s.add(A[i]);
        }
 
        for(int i = 0; i < A.length; i++)
        {
           if(s.contains(i))
             A[i] = i;
           else
             A[i] = -1;
        }
 
      return A;
}
 
    // Driver code
    public static void main(String[] args)
    {
        int A[] = {-1, -1, 6, 1, 9,
                    3, 2, -1, 4,-1};
                     
        // Function calling
        System.out.println(Arrays.toString(fix(A)));
    }
}

蟒蛇3

# Python3 program for rearrange an
# array such that arr[i] = i.
 
# Function to rearrange an array
# such that arr[i] = i.
def fix(A):
    s = set()
     
    # Storing all the values in the Set
    for i in range(len(A)):
        s.add(A[i])
 
    for i in range(len(A)):
       
        # check for item if present in set
        if i in s:
            A[i] = i
        else:
            A[i] = -1
    return A
     
# Driver code
if __name__ == "__main__":
    A = [-1, -1, 6, 1, 9,
          3, 2, -1, 4,-1]
    print(fix(A))
 
# This code is contributed by Chitranayal

C#

using System;
using System.Collections.Generic;
public class main{
    static void fix(int[] a,int n){
       HashSet hs=new HashSet();
         
        // Traverse the array
        // and add each element
        // to the HashSet
        for(int i=0;i i=n-1
        for(int i=0;i

Javascript


输出
-1 1 2 3 4 -1 6 -1 -1 9

另一种方法(交换数组中的元素):
1) 遍历数组中的元素
2) 如果 arr[i] >= 0 && arr[i] != i,把 arr[i] 放在 i 处(将 arr[i] 与 arr[arr[i]] 交换)

下面是上述方法的实现。

C++

// C++ program for rearrange an
// array such that arr[i] = i.
#include 
 
void fixArray(int arr[], int n)
{
 
    for (int i = 0; i < n;)
    {
        if (arr[i] >= 0 && arr[i] != i)
            arr[arr[i]] = (arr[arr[i]] + arr[i])
                          - (arr[i] = arr[arr[i]]);
        else
            i++;
    }
}
 
// Driver Code
int main()
{
    int arr[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Fucnction Call
    fixArray(arr, n);
 
    // Print output
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}
 
// This Code is Contributed by Adarsh_Verma

Java

// Java program for rearrange an
// array such that arr[i] = i.
import java.util.Arrays;
 
class Program
{
    public static void main(String[] args)
    {
        int[] arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 };
        for (int i = 0; i < arr.length;)
        {
            if (arr[i] >= 0 && arr[i] != i)
            {
                int ele = arr[arr[i]];
                arr[arr[i]] = arr[i];
                arr[i] = ele;
            }
            else
            {
                i++;
            }
        }
        System.out.println(Arrays.toString(arr));
    }
}
 
/* This Java code is contributed by PrinciRaj1992*/

蟒蛇3

# Python3 program for rearrange an
# array such that arr[i] = i.
if __name__ == "__main__":
 
    arr = [-1, -1, 6, 1, 9,
           3, 2, -1, 4, -1]
    n = len(arr)
    i = 0
    while i < n:
 
        if (arr[i] >= 0 and arr[i] != i):
            (arr[arr[i]],
             arr[i]) = (arr[i],
                        arr[arr[i]])
        else:
            i += 1
 
    for i in range(n):
        print(arr[i], end=" ")
 
# This code is contributed by Chitranayal

C#

// C# program for rearrange an
// array such that arr[i] = i.
using System;
 
namespace GFG {
 
class Program {
    static void Main(string[] args)
    {
        int[] arr = { -1, -1, 6, 1, 9,
                     3, 2, -1, 4, -1 };
        for (int i = 0; i < arr.Length;)
        {
            if (arr[i] >= 0 && arr[i] != i)
            {
                int ele = arr[arr[i]];
                arr[arr[i]] = arr[i];
                arr[i] = ele;
            }
            else
            {
                i++;
            }
        }
        Console.WriteLine(String.Join(",", arr));
    }
}
}
// This code is contributed by
// Venkata VardhiReddy(venkata)

Javascript


输出
-1 1 2 3 4 -1 6 -1 -1 9

时间复杂度: O(n)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程