Advertisement
BorisTad

Untitled

Dec 4th, 2024
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | Source Code | 0 0
  1. #include <iostream>
  2.  
  3. int main() {
  4.     int size;
  5.  
  6.     // Accept the size of the array
  7.     std::cout << "Enter the size of the array: ";
  8.     std::cin >> size;
  9.  
  10.     // Dynamically allocate the array
  11.     int* arr = new int[size];
  12.  
  13.     // Accept elements of the array
  14.     std::cout << "Enter " << size << " elements of the array: ";
  15.     for (int i = 0; i < size; i++) {
  16.         std::cin >> arr[i];
  17.     }
  18.  
  19.     // Step 1: Detect all numbers with duplicates
  20.     const int RANGE = 1000; // Adjust RANGE for the expected value range
  21.     int count[RANGE] = {0};
  22.  
  23.     for (int i = 0; i < size; i++) {
  24.         count[arr[i]]++; // Count occurrences of each number
  25.     }
  26.  
  27.     // Mark numbers with duplicates
  28.     bool hasDuplicates[RANGE] = {false};
  29.     for (int i = 0; i < RANGE; i++) {
  30.         if (count[i] > 1) {
  31.             hasDuplicates[i] = true;
  32.         }
  33.     }
  34.  
  35.     // Step 2: Remove only one duplicate of each detected duplicate number from the end
  36.     for (int i = size - 1; i >= 0; i--) {
  37.         if (hasDuplicates[arr[i]]) {
  38.             hasDuplicates[arr[i]] = false; // Ensure only one is removed
  39.             // Shift elements to the left
  40.             for (int j = i; j < size - 1; j++) {
  41.                 arr[j] = arr[j + 1];
  42.             }
  43.             size--; // Reduce logical size
  44.         }
  45.     }
  46.  
  47.     // Output the resulting array
  48.     std::cout << "Resulting array: ";
  49.     for (int i = 0; i < size; i++) {
  50.         std::cout << arr[i] << " ";
  51.     }
  52.     std::cout << std::endl;
  53.  
  54.     // Free allocated memory
  55.     delete[] arr;
  56.  
  57.     return 0;
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement