📜  连接给定数组两次

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

连接给定数组两次

给定一个包含N个元素的数组arr[] ,任务是将它连接两次,即通过将给定数组的副本附加到自身来创建一个大小为2*N的数组。

例子:

方法:给定的问题是一个基于实现的问题。可以通过创建大小为2*N的数组newArr[]来解决。使用[0, N)范围内的变量i迭代给定数组arr[]并附加分配newArr[i] = arr[i]newArr[i + N] = arr[i]

下面是上述方法的实现:

C++
// C++ program of the above approach
#include 
using namespace std;
 
// Function to concatenate the
// given array arr[] twice
void concatTwice(int* arr, int N)
{
    // Stores array after
    // concatenation
    int newArr[2 * N];
 
    // Loop to iterate arr[]
    for (int i = 0; i < N; i++) {
        newArr[i] = arr[i];
        newArr[i + N] = arr[i];
    }
 
    // Print Answer
    for (int i = 0; i < 2 * N; i++) {
        cout << newArr[i] << " ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    concatTwice(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
  // Function to concatenate the
  // given array arr[] twice
  static void concatTwice(int arr[], int N)
  {
    // Stores array after
    // concatenation
    int newArr[] = new int[2 * N];
 
    // Loop to iterate arr[]
    for (int i = 0; i < N; i++) {
      newArr[i] = arr[i];
      newArr[i + N] = arr[i];
    }
 
    // Print Answer
    for (int i = 0; i < 2 * N; i++) {
      System.out.print(newArr[i] + " ");
    }
  }
 
  // Driver Code
  public static void main (String[] args) {
    int arr[] = { 1, 2, 3 };
    int N = arr.length;
 
    concatTwice(arr, N);
  }
}
 
// This code is contributed by hrithikgarg03188


Python3
# Python program of the above approach
 
# Function to concatenate the
# given array arr[] twice
def concatTwice(arr, N):
 
    # Stores array after
    # concatenation
    newArr = [0] * (2 * N)
 
    # Loop to iterate arr[]
    for i in range(N):
        newArr[i] = arr[i]
        newArr[i + N] = arr[i]
 
    # Print Answer
    for i in range(0, 2 * N):
        print(newArr[i], end=" ")
 
# Driver Code
arr = [1, 2, 3]
N = len(arr)
 
concatTwice(arr, N)
 
# This code is contributed by gfgking


C#
// C# program for the above approach
using System;
class GFG {
 
  // Function to concatenate the
  // given array arr[] twice
  static void concatTwice(int []arr, int N)
  {
     
    // Stores array after
    // concatenation
    int []newArr = new int[2 * N];
 
    // Loop to iterate arr[]
    for (int i = 0; i < N; i++) {
      newArr[i] = arr[i];
      newArr[i + N] = arr[i];
    }
 
    // Print Answer
    for (int i = 0; i < 2 * N; i++) {
      Console.Write(newArr[i] + " ");
    }
  }
 
  // Driver Code
  public static void Main () {
    int []arr = { 1, 2, 3 };
    int N = arr.Length;
 
    concatTwice(arr, N);
  }
}
 
// This code is contributed by Samim Hossain Mondal


Javascript



输出
1 2 3 1 2 3 

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