📌  相关文章
📜  填充 N 个自然数数组中的缺失数,使得 arr[i] 不等于 i

📅  最后修改于: 2021-09-02 07:36:48             🧑  作者: Mango

给定一个由N 个自然数组成的未排序数组arr[]和缺失数为0使得arr[i] ≠ i ,任务是在不改变初始顺序的情况下找到并填充这些缺失数。请注意,数组只能包含一次从 1 到 N 的数字。

例子:

方法:

  • 将所有未填充的索引存储在数组unfilled_indices[] 中。即,对于所有i使得arr[i] = 0。
  • 还要存储在数组missing[]中缺失的所有元素。这可以通过首先插入从1N 的所有元素然后删除所有不为0 的元素来完成
  • 简单地迭代unfilled_indices[]数组并开始分配存储在missing[]数组中的所有元素,可能从后向获取每个元素(以避免任何i得到arr[i] = i )。
  • 现在有可能最多一个索引可以得到相同的arr[i] = i 。在检查其他索引是否应存在于unfilled_indices[]之后,只需与它交换任何其他元素。
  • 打印新数组。

下面是上述方法的实现:

C++
// C++ implementation of above approach
 
#include 
using namespace std;
 
// Function to print array
void printArray(int[], int);
 
// Function to fill the position
// with arr[i] = 0
void solve(int arr[], int n)
{
 
    set unfilled_indices;
    set missing;
 
    // Inserting all elements in
    // missing[] set from 1 to N
    for (int i = 1; i < n; i++)
        missing.insert(i);
 
    for (int i = 1; i < n; i++) {
 
        // Inserting unfilled positions
        if (arr[i] == 0)
            unfilled_indices.insert(i);
 
        // Removing allocated_elements
        else {
            auto it = missing.find(arr[i]);
            missing.erase(it);
        }
    }
    auto it2 = missing.end();
    it2--;
 
    // Loop for filling the positions
    // with arr[i] != i
    for (auto it = unfilled_indices.begin();
         it != unfilled_indices.end();
         it++, it2--) {
        arr[*it] = *it2;
    }
    int pos = 0;
 
    // Checking for any arr[i] = i
    for (int i = 1; i < n; i++) {
        if (arr[i] == i) {
            pos = i;
        }
    }
 
    int x;
 
    // Finding the suitable position
    // in the array to swap with found i
    // for which arr[i] = i
    if (pos != 0) {
        for (int i = 1; i < n; i++) {
            if (pos != i) {
 
                // Checking if the position
                // is present in unfilled_position
                if (unfilled_indices.find(i)
                    != unfilled_indices.end()) {
 
                    // Swapping arr[i] & arr[pos]
                    // (arr[pos] = pos)
                    x = arr[i];
                    arr[i] = pos;
                    arr[pos] = x;
                    break;
                }
            }
        }
    }
    printArray(arr, n);
}
 
// Function to Print the array
void printArray(int arr[], int n)
{
    for (int i = 1; i < n; i++)
        cout << arr[i] << " ";
}
 
// Driver Code
int main()
{
    int arr[] = { 0, 7, 4, 0,
                  3, 0, 5, 1 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    solve(arr, n);
    return 0;
}


Java
// Java implementation of above approach
import java.io.*;
import java.util.*;
class GFG
{
 
  // Function to fill the position
  // with arr[i] = 0
  static void solve(int arr[], int n)
  {
    Set unfilled_indices = new HashSet();
    Set missing = new HashSet();
 
    // Inserting all elements in
    // missing[] set from 1 to N
    for (int i = 1; i < n; i++)
    {
      missing.add(i);
    }
    for (int i = 1; i < n; i++)
    {
 
      // Inserting unfilled positions
      if (arr[i] == 0)
      {
        unfilled_indices.add(i);
      }
 
      // Removing allocated_elements
      else
      {
        missing.remove(arr[i]);
      }
    }
    int[] mi = new int[missing.size()];
    int l = 0;
    for(int x:missing)
    {
      mi[l++] = x;
    }
    int m = missing.size();
 
    // Loop for filling the positions
    // with arr[i] != i
    for(int it:unfilled_indices)
    {
      arr[it] = mi[m - 1];
      m--;
    }
    int pos = 0;
 
    // Checking for any arr[i] = i
    for (int i = 1; i < n; i++)
    {
      if (arr[i] == i)
      {
        pos = i;
      }
    }
    int x;
 
    // Finding the suitable position
    // in the array to swap with found i
    // for which arr[i] = i
    if (pos != 0)
    {
      for (int i = 1; i < n; i++)
      {
        if (pos != i)
        {
 
          // Checking if the position
          // is present in unfilled_position
          if(unfilled_indices.contains(i))
          {
 
            // Swapping arr[i] & arr[pos]
            // (arr[pos] = pos)
            x = arr[i];
            arr[i] = pos;
            arr[pos] = x;
            break;
          }
        }
      }
    }
    printArray(arr, n);
  }
 
  // Function to Print the array
  static void printArray(int arr[], int n)
  {
    for (int i = 1; i < n; i++)
    {
      System.out.print(arr[i] + " ");   
    }
  }
 
  // Driver Code
  public static void main (String[] args)
  {
    int[] arr = { 0, 7, 4, 0,3, 0, 5, 1 };
    int n = arr.length;
    solve(arr, n);
  }
}
 
// This code is contributed by avanitrachhadiya2155


Python3
# Python3 implementation of above approach
 
# Function to fill the position
# with arr[i] = 0
def solve(arr, n):
     
    unfilled_indices = {}
    missing = {}
     
    # Inserting all elements in
    # missing[] set from 1 to N
    for i in range(n):
        missing[i] = 1
 
    for i in range(1, n):
 
        # Inserting unfilled positions
        if (arr[i] == 0):
            unfilled_indices[i] = 1
             
        # Removing allocated_elements
        else:
            del missing[arr[i]]
 
    it2 = list(missing.keys())
    m = len(it2)
 
    # Loop for filling the positions
    # with arr[i] != i
    for it in unfilled_indices:
        arr[it] = it2[m - 1]
        m -= 1
 
    pos = 0
 
    # Checking for any arr[i] = i
    for i in range(1, n):
        if (arr[i] == i):
            pos = i
 
    x  = 0
 
    # Finding the suitable position
    # in the array to swap with found i
    # for which arr[i] = i
    if (pos != 0):
        for i in range(1, n):
            if (pos != i):
                 
                # Checking if the position
                # is present in unfilled_position
                if i in unfilled_indices:
                     
                    # Swapping arr[i] & arr[pos]
                    # (arr[pos] = pos)
                    x = arr[i]
                    arr[i] = pos
                    arr[pos] = x
                    break
 
    printArray(arr, n)
 
# Function to Print the array
def printArray(arr, n):
     
    for i in range(1, n):
        print(arr[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 0, 7, 4, 0, 3, 0, 5, 1 ]
 
    n = len(arr)
 
    solve(arr, n)
 
# This code is contributed by mohit kumar 29


C#
// C# implementation of above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to fill the position
// with arr[i] = 0
static void solve(int[] arr, int n)
{
    HashSet unfilled_indices = new HashSet();
    HashSet missing = new HashSet();
     
    // Inserting all elements in
    // missing[] set from 1 to N
    for(int i = 1; i < n; i++)
    {
        missing.Add(i);
    }
    for(int i = 1; i < n; i++)
    {
         
        // Inserting unfilled positions
        if (arr[i] == 0)
        {
            unfilled_indices.Add(i);
        }
         
        // Removing allocated_elements
        else
        {
            missing.Remove(arr[i]);
        }
    }
     
    int[] mi = new int[missing.Count];
    int l = 0;
     
    foreach(int x in missing)
    {
        mi[l++] = x;
    }
     
    int m = missing.Count;
     
    // Loop for filling the positions
    // with arr[i] != i
    foreach(int it in unfilled_indices)
    {
        arr[it] = mi[m - 1];
        m--;
    }
    int pos = 0;
     
    // Checking for any arr[i] = i
    for(int i = 1; i < n; i++)
    {
        if (arr[i] == i)
        {
            pos = i;
        }
    }
     
    // Finding the suitable position
    // in the array to swap with found i
    // for which arr[i] = i
    if (pos != 0)
    {
        for(int i = 1; i < n; i++)
        {
            if (pos != i)
            {
                 
                // Checking if the position
                // is present in unfilled_position
                if (unfilled_indices.Contains(i))
                {
                     
                    // Swapping arr[i] & arr[pos]
                    // (arr[pos] = pos)
                    int x = arr[i];
                    arr[i] = pos;
                    arr[pos] = x;
                    break;
                }
            }
        }
    }
    printArray(arr, n);
}
 
// Function to Print the array
static void printArray(int[] arr, int n)
{
    for(int i = 1; i < n; i++)
    {
        Console.Write(arr[i] + " ");
    }
}
 
// Driver Code
static public void Main()
{
    int[] arr = { 0, 7, 4, 0, 3, 0, 5, 1 };
    int n = arr.Length;
     
    solve(arr, n);
}
}
 
// This code is contributed by rag2127


输出:
7 4 6 3 2 5 1

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live