📌  相关文章
📜  插入与它相邻的 K 的副本,因为它是数组中的每次出现

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

给定一个由N 个整数和一个整数K组成的数组arr ,任务是为原始序列中每次出现的 K 插入一个相邻的 K,然后使用 O(1) 辅助空间将数组截断为原始长度。

例子:

方法 1:使用STL 函数
这个问题可以通过使用内置函数 pop_back() 和 insert() 来解决。

下面是上述方法的实现:

C++
// C++ implementation to update each entry of zero
// with two zero entries adjacent to each other
#include 
using namespace std;
 
// Function to update each entry of zero
// with two zero entries adjacent to each other
vector duplicateK(vector& arr)
{
    int N = arr.size();
    for(int i=0;i arr
= { 1, 0, 2, 3, 0, 4, 5, 0  };
 
    vector ans = duplicateK(arr);
 
    for (int i = 0; i < ans.size(); i++)
        cout << ans[i] << " ";
 
    return 0;
}


Java
// Java implementation to update each
// entry of zero with two zero entries
// adjacent to each other
import java.util.*;
 
class GFG{
 
// Function to update each entry of
// zero with two zero entries
// adjacent to each other
static Vector duplicateK(Vector arr)
{
    int N = arr.size();
    for(int i = 0; i < N; i++)
    {
       if(arr.get(i) == 0)
       {
            
           // Insert an adjacent 0
           arr.add(i + 1, 0);
            
           i++;
            
           // Pop the last element
           arr.remove(arr.size() - 1);
       }
    }
    return arr;
}
 
// Driver code
public static void main(String[] args)
{
    Integer []arr = { 1, 0, 2, 3, 0, 4, 5, 0 };
     
    Vector vec = new Vector();;
    for(int i = 0; i < arr.length; i++)
       vec.add(arr[i]);
         
    Vector ans = duplicateK(vec);
 
    for(int i = 0; i < ans.size(); i++)
       System.out.print(ans.get(i) + " ");
}
}
 
// This code is contributed by gauravrajput1


C#
// C# implementation to update each
// entry of zero with two zero entries
// adjacent to each other
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to update each entry of
// zero with two zero entries
// adjacent to each other
static List duplicateK(List arr)
{
    int N = arr.Count;
    for(int i = 0; i < N; i++)
    {
        if(arr[i] == 0)
        {
                 
            // Insert an adjacent 0
            arr.Insert(i + 1, 0);
                 
            i++;
                 
            // Pop the last element
            arr.RemoveAt(arr.Count - 1);
        }
    }
    return arr;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 1, 0, 2, 3, 0, 4, 5, 0 };
     
    List vec = new List();;
    for(int i = 0; i < arr.Length; i++)
    vec.Add(arr[i]);
         
    List ans = duplicateK(vec);
 
    for(int i = 0; i < ans.Count; i++)
    Console.Write(ans[i] + " ");
}
}
 
// This code is contributed by gauravrajput1


Javascript


C++
// C++ implementation to update each entry of zero
// with two zero entries adjacent to each other
#include 
using namespace std;
 
// Function to update each entry of zero
// with two zero entries adjacent to each other
vector duplicateZeros(vector& arr)
{
    const int N = arr.size();
 
    // Find the count of total number of zeros
    int cnt = count(arr.begin(), arr.end(), 0);
 
    // Variable to store index where elements
    // will be written in the final array
    int write_idx = N + cnt - 1;
 
    // Variable to point the current index
    int curr = N - 1;
 
    while (curr >= 0 && write_idx >= 0) {
        // Keep the current element to its correct
        // position, if that is within teh size N
        if (write_idx < N)
            arr[write_idx] = arr[curr];
 
        write_idx -= 1;
 
        // Check if the current element is also
        // zero then again write its duplicate
        if (arr[curr] == 0) {
            if (write_idx < N)
                arr[write_idx] = 0;
 
            write_idx -= 1;
        }
 
        --curr;
    }
 
    // Return the final result
    return arr;
}
 
// Driver code
int main(int argc, char* argv[])
{
    vector arr = { 1, 0, 2, 3, 0, 4, 5, 0 };
 
    vector ans = duplicateZeros(arr);
 
    for (int i = 0; i < ans.size(); i++)
        cout << ans[i] << " ";
 
    return 0;
}


Java
// Java implementation to update
// each entry of zero with two zero
// entries adjacent to each other
class GFG{
 
// Function to update each
// entry of zero with two zero
// entries adjacent to each other
static int[] duplicateZeros(int []arr)
{
     
    int N = arr.length;
     
    // Find the count of
    // total number of zeros
    int cnt = count(arr, 0);
     
    // Variable to store index
    // where elements will be
    // written in the final array
    int write_idx = N + cnt - 1;
     
    // Variable to point the current index
    int curr = N - 1;
     
    while (curr >= 0 && write_idx >= 0)
    {
         
        // Keep the current element
        // to its correctposition, if
        // that is within teh size N
        if (write_idx < N)
            arr[write_idx] = arr[curr];
     
        write_idx -= 1;
     
        // Check if the current element is also
        // zero then again write its duplicate
        if (arr[curr] == 0)
        {
            if (write_idx < N)
                arr[write_idx] = 0;
                 
            write_idx -= 1;
        }
        --curr;
    }
     
    // Return the final result
    return arr;
}
 
static int count(int []arr, int num)
{
    int ans = 0;
    for(int i : arr)
     
       if(i == num)
          ans++;
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    int []arr = { 1, 0, 2, 3, 0, 4, 5, 0 };
    int []ans = duplicateZeros(arr);
 
    for(int i = 0; i < ans.length; i++)
       System.out.print(ans[i] + " ");
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 implementation to update each entry of zero
# with two zero entries adjacent to each other
 
# Function to update each entry of zero
# with two zero entries adjacent to each other
def duplicateZeros(arr):
 
    N = len(arr)
 
    # Find the count of total number of zeros
    cnt = arr.count(0)
 
    # Variable to store index where elements
    # will be written in the final array
    write_idx = N + cnt - 1
 
    # Variable to point the current index
    curr = N - 1
 
    while (curr >= 0 and write_idx >= 0):
         
        # Keep the current element to its correct
        # position, if that is within the size N
        if (write_idx < N):
            arr[write_idx] = arr[curr]
 
        write_idx -= 1
 
        # Check if the current element is also
        # zero then again write its duplicate
        if (arr[curr] == 0):
            if (write_idx < N):
                arr[write_idx] = 0
 
            write_idx -= 1
 
        curr -= 1
 
    # Return the final result
    return arr
 
# Driver Code
arr = [ 1, 0, 2, 3, 0, 4, 5, 0 ]
 
ans = duplicateZeros(arr)
for i in range(len(ans)):
    print(ans[i], end = " ")
     
# This code is contributed by divyamohan123


C#
// C# implementation to update
// each entry of zero with two zero
// entries adjacent to each other
using System;
 
class GFG{
 
// Function to update each
// entry of zero with two zero
// entries adjacent to each other
static int[] duplicateZeros(int []arr)
{
    int N = arr.Length;
     
    // Find the count of
    // total number of zeros
    int cnt = count(arr, 0);
     
    // Variable to store index
    // where elements will be
    // written in the readonly array
    int write_idx = N + cnt - 1;
     
    // Variable to point the
    // current index
    int curr = N - 1;
     
    while (curr >= 0 && write_idx >= 0)
    {
         
        // Keep the current element
        // to its correctposition, if
        // that is within teh size N
        if (write_idx < N)
            arr[write_idx] = arr[curr];
     
        write_idx -= 1;
     
        // Check if the current element is also
        // zero then again write its duplicate
        if (arr[curr] == 0)
        {
            if (write_idx < N)
                arr[write_idx] = 0;
                 
            write_idx -= 1;
        }
        --curr;
    }
     
    // Return the readonly result
    return arr;
}
 
static int count(int []arr, int num)
{
    int ans = 0;
    foreach(int i in arr)
    {
        if(i == num)
           ans++;
    }
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 1, 0, 2, 3, 0, 4, 5, 0 };
    int []ans = duplicateZeros(arr);
 
    for(int i = 0; i < ans.Length; i++)
       Console.Write(ans[i] + " ");
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:

1 0 0 2 3 0 0 4 

方法 2:使用两个指针技术

  • 由于每个 K 都需要用两个彼此相邻的 K 个条目进行更新,因此数组的长度增加的量等于原始数组 arr[] 中存在的 K 的数量
  • 找到 K 的总数,然后我们假设我们有一个数组,有足够的空间来容纳每个元素。
  • 初始化一个变量write_idx ,该变量将指向这个虚数组末尾的索引和当前数组末尾的另一个指针curr ,即 arr[N-1]。
  • 从最后开始迭代,对于每个元素,我们假设我们正在将元素复制到其当前位置,但仅当 write_idx < N 时才复制,并且每次都保持更新 write_idx。对于值为零的元素,将其写入两次。

下面是上述方法的实现:

C++

// C++ implementation to update each entry of zero
// with two zero entries adjacent to each other
#include 
using namespace std;
 
// Function to update each entry of zero
// with two zero entries adjacent to each other
vector duplicateZeros(vector& arr)
{
    const int N = arr.size();
 
    // Find the count of total number of zeros
    int cnt = count(arr.begin(), arr.end(), 0);
 
    // Variable to store index where elements
    // will be written in the final array
    int write_idx = N + cnt - 1;
 
    // Variable to point the current index
    int curr = N - 1;
 
    while (curr >= 0 && write_idx >= 0) {
        // Keep the current element to its correct
        // position, if that is within teh size N
        if (write_idx < N)
            arr[write_idx] = arr[curr];
 
        write_idx -= 1;
 
        // Check if the current element is also
        // zero then again write its duplicate
        if (arr[curr] == 0) {
            if (write_idx < N)
                arr[write_idx] = 0;
 
            write_idx -= 1;
        }
 
        --curr;
    }
 
    // Return the final result
    return arr;
}
 
// Driver code
int main(int argc, char* argv[])
{
    vector arr = { 1, 0, 2, 3, 0, 4, 5, 0 };
 
    vector ans = duplicateZeros(arr);
 
    for (int i = 0; i < ans.size(); i++)
        cout << ans[i] << " ";
 
    return 0;
}

Java

// Java implementation to update
// each entry of zero with two zero
// entries adjacent to each other
class GFG{
 
// Function to update each
// entry of zero with two zero
// entries adjacent to each other
static int[] duplicateZeros(int []arr)
{
     
    int N = arr.length;
     
    // Find the count of
    // total number of zeros
    int cnt = count(arr, 0);
     
    // Variable to store index
    // where elements will be
    // written in the final array
    int write_idx = N + cnt - 1;
     
    // Variable to point the current index
    int curr = N - 1;
     
    while (curr >= 0 && write_idx >= 0)
    {
         
        // Keep the current element
        // to its correctposition, if
        // that is within teh size N
        if (write_idx < N)
            arr[write_idx] = arr[curr];
     
        write_idx -= 1;
     
        // Check if the current element is also
        // zero then again write its duplicate
        if (arr[curr] == 0)
        {
            if (write_idx < N)
                arr[write_idx] = 0;
                 
            write_idx -= 1;
        }
        --curr;
    }
     
    // Return the final result
    return arr;
}
 
static int count(int []arr, int num)
{
    int ans = 0;
    for(int i : arr)
     
       if(i == num)
          ans++;
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    int []arr = { 1, 0, 2, 3, 0, 4, 5, 0 };
    int []ans = duplicateZeros(arr);
 
    for(int i = 0; i < ans.length; i++)
       System.out.print(ans[i] + " ");
}
}
 
// This code is contributed by Amit Katiyar

蟒蛇3

# Python3 implementation to update each entry of zero
# with two zero entries adjacent to each other
 
# Function to update each entry of zero
# with two zero entries adjacent to each other
def duplicateZeros(arr):
 
    N = len(arr)
 
    # Find the count of total number of zeros
    cnt = arr.count(0)
 
    # Variable to store index where elements
    # will be written in the final array
    write_idx = N + cnt - 1
 
    # Variable to point the current index
    curr = N - 1
 
    while (curr >= 0 and write_idx >= 0):
         
        # Keep the current element to its correct
        # position, if that is within the size N
        if (write_idx < N):
            arr[write_idx] = arr[curr]
 
        write_idx -= 1
 
        # Check if the current element is also
        # zero then again write its duplicate
        if (arr[curr] == 0):
            if (write_idx < N):
                arr[write_idx] = 0
 
            write_idx -= 1
 
        curr -= 1
 
    # Return the final result
    return arr
 
# Driver Code
arr = [ 1, 0, 2, 3, 0, 4, 5, 0 ]
 
ans = duplicateZeros(arr)
for i in range(len(ans)):
    print(ans[i], end = " ")
     
# This code is contributed by divyamohan123

C#

// C# implementation to update
// each entry of zero with two zero
// entries adjacent to each other
using System;
 
class GFG{
 
// Function to update each
// entry of zero with two zero
// entries adjacent to each other
static int[] duplicateZeros(int []arr)
{
    int N = arr.Length;
     
    // Find the count of
    // total number of zeros
    int cnt = count(arr, 0);
     
    // Variable to store index
    // where elements will be
    // written in the readonly array
    int write_idx = N + cnt - 1;
     
    // Variable to point the
    // current index
    int curr = N - 1;
     
    while (curr >= 0 && write_idx >= 0)
    {
         
        // Keep the current element
        // to its correctposition, if
        // that is within teh size N
        if (write_idx < N)
            arr[write_idx] = arr[curr];
     
        write_idx -= 1;
     
        // Check if the current element is also
        // zero then again write its duplicate
        if (arr[curr] == 0)
        {
            if (write_idx < N)
                arr[write_idx] = 0;
                 
            write_idx -= 1;
        }
        --curr;
    }
     
    // Return the readonly result
    return arr;
}
 
static int count(int []arr, int num)
{
    int ans = 0;
    foreach(int i in arr)
    {
        if(i == num)
           ans++;
    }
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 1, 0, 2, 3, 0, 4, 5, 0 };
    int []ans = duplicateZeros(arr);
 
    for(int i = 0; i < ans.Length; i++)
       Console.Write(ans[i] + " ");
}
}
 
// This code is contributed by Amit Katiyar

Javascript


输出:
1 0 0 2 3 0 0 4

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

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