📜  在给定的 1 到 N 排列数组中查找所有重复和缺失的数字

📅  最后修改于: 2022-05-13 01:56:07.164000             🧑  作者: Mango

在给定的 1 到 N 排列数组中查找所有重复和缺失的数字

给定一个由前N个自然数组成的大小为N的数组arr[] ,任务是在给定数组的[1, N]范围内找到所有重复和缺失的数字。

例子:

方法:给定的问题可以使用本文中讨论的想法来解决,其中只有一个元素是重复的,另一个是重复的。请按照以下步骤解决给定的问题:

  • 初始化一个数组,比如missing[] ,它存储丢失的元素。
  • 初始化一个集合,比如存储重复元素的副本。
  • 使用变量i遍历给定的数组arr[]并执行以下步骤:
    • 如果arr[i] != arr[arr[i] – 1]的值为真,则当前元素不等于如果所有数字都存在于1N的位置。所以交换arr[i]arr[arr[i] – 1]
    • 否则,这意味着arr[arr[i] – 1]中存在相同的元素。
  • 使用变量i遍历给定数组arr[] ,如果arr[i]的值与(i + 1)不同,则缺失元素为(i + 1) ,重复元素为arr[i]
  • 完成上述步骤后,将missing[]duplicate[]中存储的元素打印为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the duplicate and
// the missing elements over the range
// [1, N]
void findElements(int arr[], int N)
{
    int i = 0;
 
    // Stores the missing and duplicate
    // numbers in the array arr[]
    vector missing;
    set duplicate;
 
    // Making an iterator for set
    set::iterator it;
 
    // Traverse the given array arr[]
    while (i != N) {
        cout << i << " # " ;
        // Check if the current element
        // is not same as the element at
        // index arr[i] - 1, then swap
        if (arr[i] != arr[arr[i] - 1]) {
            swap(arr[i], arr[arr[i] - 1]);
        }
 
        // Otherwise, increment the index
        else {
            i++;
        }
    }
 
    // Traverse the array again
    for (i = 0; i < N; i++) {
 
        // If the element is not at its
        // correct position
        if (arr[i] != i + 1) {
 
            // Stores the missing and the
            // duplicate elements
            missing.push_back(i + 1);
            duplicate.insert(arr[i]);
        }
    }
 
    // Print the Missing Number
    cout << "Missing Numbers: ";
    for (auto& it : missing)
        cout << it << ' ';
 
    // Print the Duplicate Number
    cout << "\nDuplicate Numbers: ";
    for (auto& it : duplicate)
        cout << it << ' ';
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 2, 2, 4, 5, 7 };
    int N = sizeof(arr) / sizeof(arr[0]);
    findElements(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.ArrayList;
import java.util.HashSet;
 
class GFG {
 
    // Function to find the duplicate and
    // the missing elements over the range
    // [1, N]
    static void findElements(int arr[], int N) {
        int i = 0;
 
        // Stores the missing and duplicate
        // numbers in the array arr[]
        ArrayList missing = new ArrayList();
        HashSet duplicate = new HashSet();
 
        // Traverse the given array arr[]
        while (i != N) {
            // Check if the current element
            // is not same as the element at
            // index arr[i] - 1, then swap
            if (arr[i] != arr[arr[i] - 1]) {
                int temp = arr[i];
                arr[i] = arr[arr[i] - 1];
                arr[temp - 1] = temp;
            }
 
            // Otherwise, increment the index
            else {
                i++;
            }
        }
 
        // Traverse the array again
        for (i = 0; i < N; i++) {
 
            // If the element is not at its
            // correct position
            if (arr[i] != i + 1) {
 
                // Stores the missing and the
                // duplicate elements
                missing.add(i + 1);
                duplicate.add(arr[i]);
            }
        }
 
        // Print the Missing Number
        System.out.print("Missing Numbers: ");
        for (Integer itr : missing)
            System.out.print(itr + " ");
 
        // Print the Duplicate Number
        System.out.print("\nDuplicate Numbers: ");
        for (Integer itr : duplicate)
            System.out.print(itr + " ");
    }
 
    // Driver code
    public static void main(String args[]) {
        int arr[] = { 1, 2, 2, 2, 4, 5, 7 };
        int N = arr.length;
        findElements(arr, N);
    }
 
}
 
// This code is contributed by gfgking.


Python3
# Python3 program for the above approach
 
# Function to find the duplicate and
# the missing elements over the range
# [1, N]
def findElements(arr, N) :
    i = 0;
 
    # Stores the missing and duplicate
    # numbers in the array arr[]
    missing = [];
    duplicate = set();
 
    # Traverse the given array arr[]
    while (i != N) :
         
        # Check if the current element
        # is not same as the element at
        # index arr[i] - 1, then swap
        if (arr[i] != arr[arr[i] - 1]) :
             
            t = arr[i]
            arr[i] = arr[arr[i] - 1]
            arr[t - 1]  = t
             
        # Otherwise, increment the index
        else :
            i += 1;
 
    # Traverse the array again
    for i in range(N) :
         
        # If the element is not at its
        # correct position
        if (arr[i] != i + 1) :
 
            # Stores the missing and the
            # duplicate elements
            missing.append(i + 1);
            duplicate.add(arr[i]);
 
    # Print the Missing Number
    print("Missing Numbers: ",end="");
     
    for it in missing:
        print(it,end=" ");
 
    # Print the Duplicate Number
    print("\nDuplicate Numbers: ",end="");
     
    for it in list(duplicate) :
        print(it, end=' ');
 
# Driver code
if __name__ == "__main__" :
 
    arr = [ 1, 2, 2, 2, 4, 5, 7 ];
    N = len(arr);
    findElements(arr, N);
 
    # This code is contributed by AnkThon


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
 
  // Function to find the duplicate and
  // the missing elements over the range
  // [1, N]
  static void findElements(int[] arr, int N)
  {
    int i = 0;
 
    // Stores the missing and duplicate
    // numbers in the array arr[]
    List missing = new List();
    HashSet duplicate = new HashSet();
 
    // Traverse the given array arr[]
    while (i != N) {
      // Check if the current element
      // is not same as the element at
      // index arr[i] - 1, then swap
      if (arr[i] != arr[arr[i] - 1]) {
        int temp = arr[i];
        arr[i] = arr[arr[i] - 1];
        arr[temp - 1] = temp;
      }
 
      // Otherwise, increment the index
      else {
        i++;
      }
    }
 
    // Traverse the array again
    for (i = 0; i < N; i++) {
 
      // If the element is not at its
      // correct position
      if (arr[i] != i + 1) {
 
        // Stores the missing and the
        // duplicate elements
        missing.Add(i + 1);
        duplicate.Add(arr[i]);
      }
    }
 
    // Print the Missing Number
    Console.Write("Missing Numbers: ");
    foreach(int itr in missing)
      Console.Write(itr + " ");
 
    // Print the Duplicate Number
    Console.Write("\nDuplicate Numbers: ");
    foreach(int itr in duplicate)
      Console.Write(itr + " ");
  }
 
  // Driver code
  public static void Main()
  {
    int[] arr = { 1, 2, 2, 2, 4, 5, 7 };
    int N = arr.Length;
    findElements(arr, N);
  }
}
 
// This code is contributed by ukasp.


Javascript


输出:
Missing Numbers: 3 6 
Duplicate Numbers: 2

时间复杂度: O(N)
辅助空间: O(N)