Combinar los elementos en subarreglo de todos los elementos pares del Array

Dado un arreglo arr[] que contiene N números, la tarea es fusionar el subarreglo de números pares consecutivos reemplazando todos los números pares consecutivos por el primer elemento par de ese subarreglo.
Nota: Se dice que una serie de enteros pares es consecutiva si hay al menos tres números pares en la serie dada. Por lo tanto, fusione elementos en un subarreglo que tenga al menos 3 números pares consecutivos.
Ejemplos:

Entrada: arr[] = {2, 2, 2, 100, 5, 4, 2, 9, 10, 88, 24} 
Salida: 2 5 4 2 9 10 
Explicación: 
La serie dada contiene dos subsecuencias pares consecutivas. Ellos son: 
{2, 2, 2, 100}, {10, 88, 24}. Las dos subsecuencias deben fusionarse con el primer elemento de la subserie. 
Por lo tanto, {2, 2, 2, 100} se reemplaza por 2 y {10, 88, 24} se reemplaza por 10 en la serie original.
Entrada: arr[] = {2, 4, 5, 3, 6, 8, 10, 3, 4} 
Salida: 2 4 5 3 6 3 4

Enfoque: Para resolver este problema, primero debemos encontrar si existe una subsecuencia par consecutiva con un tamaño mayor que tres. Por lo tanto, la idea es iterar a través de la array dada y verificar si un número es par o no.

  • Atraviesa la array.
  • Comprueba si el elemento es par o no.
  • Si es par, crea una array temporal para almacenar los siguientes números pares continuos hasta que el siguiente número sea impar.
  • Continúe agregando los elementos en la array temporal hasta que ocurra un número impar.
  • Si el tamaño de esta array temporal es mayor que tres, elimine estos elementos de la array dada y reemplácelos con el primer elemento de esta array temporal.
  • Vacíe la array temporal para calcular el siguiente conjunto de subsecuencias pares.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program to merge the array
// as per the given condition
#include<bits/stdc++.h>
using namespace std;
 
// Function to merge the array
// as per the given condition
vector<int> merge(vector<int> arr)
{
     
    // Variable to store the final
    // sequence
    vector<int> ans;
 
    // Temporary array to store the
    // even numbers while traversing
    vector<int> e;
    int i = 0;
    int j = 0;
    int count = 0;
     
    // Iterating through the array
    while(i < arr.size())
    {
         
        // If the element is even
        if(arr[i] % 2 == 0)
        {
            j = i;
             
            // Iterating till an odd element
            // is found
            while(j < arr.size())
            {
                 
                // Keep appending into the
                // temporary array if the
                // even number is occurred
                if (arr[j] % 2 == 0)
                {
                    e.push_back(arr[j]);
                    count += 1;
                }
 
                // Break if an odd number
                // has occurred
                else
                    break;
                 
                j += 1;
            }
     
            // If the series has at least
            // three elements, then merge
            if(count >= 3)
               ans.push_back(e[0]);
 
            // Else, add all elements to the
            // answer array
            else
            {
                for (auto i: e)
                     ans.push_back(i);
            }
                 
            // Reseting the count and
            // temp array
            count = 0;
            e.clear();
            i = j;
        }
             
        // If the element is odd, add
        // it to the answer array
        else
        {
            ans.push_back(arr[i]);
            i += 1;
        }
    }
     
    return ans;
}
         
// Driver code
int main()
{
 
    vector<int> arr({ 2, 2, 2, 100, 5, 4,
                      2, 9, 10, 88, 24 });
    vector<int> ans = merge(arr);
     
    cout << "[";
    for(int i= 0; i < ans.size(); i++)
    {
        if(i == ans.size() - 1)
        cout << ans[i] << "]";
        else
        cout << ans[i] << ", ";
    }
 
}
     
// This code is contributed by Samarth

Java

// Java program to merge the array
// as per the given condition
import java.util.*;
  
class GFG{
  
// Function to merge the array
// as per the given condition
static Vector<Integer> merge(int []arr)
{
      
    // Variable to store the final
    // sequence
    Vector<Integer> ans = new Vector<Integer>();
  
    // Temporary array to store the
    // even numbers while traversing
    Vector<Integer> e = new Vector<Integer>();
     
    int i = 0;
    int j = 0;
    int count = 0;
      
    // Iterating through the array
    while (i < arr.length)
    {
          
        // If the element is even
        if (arr[i] % 2 == 0)
        {
            j = i;
              
            // Iterating till an odd element
            // is found
            while (j < arr.length)
            {
                  
                // Keep appending into the
                // temporary array if the
                // even number is occurred
                if (arr[j] % 2 == 0)
                {
                    e.add(arr[j]);
                    count += 1;
                }
  
                // Break if an odd number
                // has occurred
                else
                    break;
                  
                j += 1;
            }
      
            // If the series has at least
            // three elements, then merge
            if (count >= 3)
               ans.add(e.get(0));
  
            // Else, add all elements to the
            // answer array
            else
            {
                for(int ii : e)
                     ans.add(ii);
            }
                  
            // Reseting the count and
            // temp array
            count = 0;
            e.clear();
            i = j;
        }
              
        // If the element is odd, add
        // it to the answer array
        else
        {
            ans.add(arr[i]);
            i += 1;
        }
    }
    return ans;
}
          
// Driver code
public static void main(String[] args)
{
  
    int []arr = { 2, 2, 2, 100, 5, 4,
                  2, 9, 10, 88, 24 };
                   
    Vector<Integer> ans = merge(arr);
      
    System.out.print("[");
    for(int i= 0; i < ans.size(); i++)
    {
        if (i == ans.size() - 1)
            System.out.print(ans.get(i) + "]");
        else
            System.out.print(ans.get(i) + ", ");
    }
}
}
 
// This code is contributed by Amit Katiyar

Python3

# Python3 program to merge the array
# as per the given condition
 
# Function to merge the array
# as per the given condition
def merge(arr):
     
    # Variable to store the final
    # sequence
    ans = []
 
    # Temporary array to store the
    # even numbers while traversing
    e =[]
    i = 0
    j = 0
    count = 0
     
    # Iterating through the array
    while i<len(arr):
     
        # If the element is even
        if(arr[i]% 2 == 0):
            j = i
             
            # Iterating till an odd element
            # is found
            while j<len(arr):
                 
                # Keep appending into the
                # temporary array if the
                # even number is occurred
                if arr[j]% 2 == 0:
                     
                    e.append(arr[j])
                    count+= 1
 
                # Break if an odd number
                # has occurred
                else:
                    break
                 
                j+= 1
     
            # If the series has at least
            # three elements, then merge
            if(count>= 3):
                ans.append(e[0])
 
            # Else, add all elements to the
            # answer array
            else:
                for i in e:
                    ans.append(i)
                 
            # Reseting the count and
            # temp array
            count = 0
            e =[]
            i = j
 
        # If the element is odd, add
        # it to the answer array
        else:
            ans.append(arr[i])
            i+= 1
             
    return ans
        
# Driver code
if __name__ == "__main__":
     
    arr = [2, 2, 2, 100, 5, 4, 2, 9, 10, 88, 24]
     
    print(merge(arr))

C#

// C# program to merge the array
// as per the given condition
using System;
using System.Collections.Generic;
class GFG{
  
// Function to merge the array
// as per the given condition
static List<int> merge(int []arr)
{
  // Variable to store the final
  // sequence
  List<int> ans = new List<int>();
 
  // Temporary array to store the
  // even numbers while traversing
  List<int> e = new List<int>();
 
  int i = 0;
  int j = 0;
  int count = 0;
 
  // Iterating through the array
  while (i < arr.Length)
  {
    // If the element is even
    if (arr[i] % 2 == 0)
    {
      j = i;
 
      // Iterating till an odd element
      // is found
      while (j < arr.Length)
      {
        // Keep appending into the
        // temporary array if the
        // even number is occurred
        if (arr[j] % 2 == 0)
        {
          e.Add(arr[j]);
          count += 1;
        }
 
        // Break if an odd number
        // has occurred
        else
          break;
 
        j += 1;
      }
 
      // If the series has at least
      // three elements, then merge
      if (count >= 3)
        ans.Add(e[0]);
 
      // Else, add all elements to the
      // answer array
      else
      {
        foreach(int ii in e)
          ans.Add(ii);
      }
 
      // Reseting the count and
      // temp array
      count = 0;
      e.Clear();
      i = j;
    }
 
    // If the element is odd, add
    // it to the answer array
    else
    {
      ans.Add(arr[i]);
      i += 1;
    }
  }
  return ans;
}
          
// Driver code
public static void Main(String[] args)
{
  int []arr = {2, 2, 2, 100, 5, 4,
               2, 9, 10, 88, 24};
 
  List<int> ans = merge(arr);
  Console.Write("[");
   
  for(int i= 0; i < ans.Count; i++)
  {
    if (i == ans.Count - 1)
      Console.Write(ans[i] + "]");
    else
      Console.Write(ans[i] + ", ");
  }
}
}
 
// This code is contributed by 29AjayKumar
Producción: 

[2, 5, 4, 2, 9, 10]



Complejidad de tiempo: O(N 2 ) , donde N es la longitud de la array.

Publicación traducida automáticamente

Artículo escrito por Riyaz_Khan_Pathan y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *