📌  相关文章
📜  通过完全删除第(arr [i] + arr [i + 1])个元素来修改数组

📅  最后修改于: 2021-05-17 18:54:43             🧑  作者: Mango

给定的阵列ARR []由第一N的自然数,其中ARR [I] = I(基于1的索引)和整数K,一个正的,则任务是打印阵列ARR []除去每隔(ARR [之后所获得的我] + ARR [I + 1])从阵列元件中的每i动作恰好K倍。

例子:

方法:给定的问题可以通过删去每(ARR [I] + ARR第[i + 1])术语从阵列中的每个i操作执行给定操作恰好K次可以解决。请按照以下步骤解决问题:

  • 使用变量i遍历[0,K – 1]范围,并执行以下步骤:
    • 在每次删除操作之后,初始化辅助数组B []以存储数组arr []的元素。
    • 遍历给定数组arr [] ,如果当前索引不能被值(arr [i] + arr [i + 1])整除,则将该元素插入数组B []中
    • 完成上述步骤后,将数组B []的所有元素插入数组arr []中
  • 完成上述步骤后,将数组arr []打印为结果数组。

下面是上述方法的实现:

Python3
# Python approach for the above approach
  
# Function to modify array by removing
# every K-th element from the array
def removeEveryKth(l, k):
    
    for i in range(0, len(l)):
        
        # Check if current element
        # is the k-th element
        if i % k == 0:
            l[i] = 0
  
    # Stores the elements after
    # removing every kth element
    arr = [0]
      
    for i in range(1, len(l)):
          
        # Append the current element
        # if it is not k-th element
        if l[i] != 0:
            arr.append(l[i])
  
    # Return the new array after
    # removing every k-th element
    return arr
  
# Function to print the array
def printArray(l):
    
    # Traverse the array l[]
    for i in range(1, len(l)):
        print(l[i], end =" ")
  
    print()
  
# Function to print the array after
# performing the given operations
# exactly k times
def printSequence(n, k):
  
    # Store first N natural numbers
    l = [int(i) for i in range(0, n + 1)]
  
    x = 1
  
    # Iterate over the range [0, k-1]
    for i in range(0, k):
  
        # Store sums of the two
        # consecutive terms
        p = l[x] + l[x + 1]
  
        # Remove every p-th
        # element from the array
        l = removeEveryKth(l, p)
          
        # Increment x by 1 for
        # the next iteration
        x += 1
      
    # Print the resultant array
    printArray(l)
  
# Driver Code
N = 8
K = 2
  
# Function Call
printSequence(N, K)


输出:
1 2 4 5 7

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