📌  相关文章
📜  将全1放在单个索引所需的最小步骤数

📅  最后修改于: 2021-04-17 19:18:15             🧑  作者: Mango

给定大小为N的二进制数组A [] ,可以将所有1 s移动到其相邻位置,任务是打印大小为N的数组res [] ,其中res [i]包含执行以下操作所需的最少步骤数:将所有1 s移至第i索引。

例子:

天真的方法:请按照以下步骤解决问题:

  1. 遍历数组。
  2. 对于每个i索引,计算将所有1 s移到第i索引所需的步骤数。
  3. 使用变量i遍历[0,N – 1]范围
    • 初始化步骤= 0。
    • 使用变量j[0,N – 1]范围内迭代
    • 如果A [j]等于1,则将abs(i – j)添加步骤中。
  4. 打印最小数。

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

高效方法:为了优化上述方法,我们的想法是使用Prefix Sum。请按照以下步骤解决此问题:

  1. 遍历数组。
  2. 初始化一个数组,例如left [],并初始化count = A [0]。
  3. [1,N – 1]范围内进行迭代,并更新left [i] = left [i – 1] + count ,其中counti左侧1 s的数量
  4. 初始化一个数组,例如right [],并初始化count = A [N – 1]。
  5. [N – 2,0]范围内进行迭代,并更新right [i] = right [i + 1] + count ,其中counti右侧1 s的数量
  6. 计算并更新res []中的最终答案,其中res [i]是左右两侧步长的总和,即res [i] = right [i] + left [i]
  7. 打印数组res []

下面是上述方法的实现:

C++
// C++ implementation of
// the above approach
#include 
using namespace std;
 
// Function to print minimum steps
// required to shift all 1s to a
// single index in a binary array
void minsteps(vector& A)
{
    // Size of array
    int n = A.size();
 
    // Used to store cummulative sum
    vector left(n, 0), right(n, 0), res(n, 0);
 
    // Initialize count
    int count = A[0];
 
    // Traverse the array in
    // forward direction
    for (int i = 1; i < n; i++) {
        // Steps needed to store all
        // previous ones to ith index
        left[i] = left[i - 1] + count;
 
        // Count number of 1s
        // present till i-th index
        count += A[i];
    }
 
    // Initialize count
    count = A[n - 1];
 
    // Traverse the array in
    // backward direction
    for (int i = n - 2; i >= 0; i--) {
        // Steps needed to store all 1s to
        // the right of i at current index
        right[i] = right[i + 1] + count;
 
        // Count number of 1s
        // present after i-th index
        count += A[i];
    }
 
    // Print the number of steps required
    for (int i = 0; i < n; i++) {
        res[i] = left[i] + right[i];
        cout << res[i] << " ";
    }
    cout << "\n";
}
 
// Driver Code
int main()
{
    vector A = { 1, 0, 1, 0 };
    minsteps(A);
}


Java
// Java program for the above approach
import java.util.*;
import java.lang.*;
class GFG
{
 
  // Function to print minimum steps
  // required to shift all 1s to a
  // single index in a binary array
  static void minsteps(int[] A)
  {
     
    // Size of array
    int n = A.length;
 
    // Used to store cummulative sum
    int[] left = new int [n];
    Arrays.fill(left, 0);
    int[] right = new int [n];
    Arrays.fill(right, 0);
    int[] res = new int [n];
    Arrays.fill(res, 0);
 
    // Initialize count
    int count = A[0];
 
    // Traverse the array in
    // forward direction
    for (int i = 1; i < n; i++) {
      // Steps needed to store all
      // previous ones to ith index
      left[i] = left[i - 1] + count;
 
      // Count number of 1s
      // present till i-th index
      count += A[i];
    }
 
    // Initialize count
    count = A[n - 1];
 
    // Traverse the array in
    // backward direction
    for (int i = n - 2; i >= 0; i--) {
      // Steps needed to store all 1s to
      // the right of i at current index
      right[i] = right[i + 1] + count;
 
      // Count number of 1s
      // present after i-th index
      count += A[i];
    }
 
    // Print the number of steps required
    for (int i = 0; i < n; i++) {
      res[i] = left[i] + right[i];
      System.out.print(res[i] + " ");
    }
    System.out.println();
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int[] A = { 1, 0, 1, 0 };
    minsteps(A);
  }
}
 
// This code is contributed by souravghosh0416.


Python3
# Python3 implementation of
# the above approach
 
# Function to prminimum steps
# required to shift all 1s to a
# single index in a binary array
def minsteps(A):
   
    # Size of array
    n = len(A)
 
    # Used to store cummulative sum
    left, right, res =[0]*n, [0]*n, [0]*n
 
    # Initialize count
    count = A[0]
 
    # Traverse the array in
    # forward direction
    for i in range(1, n):
       
        # Steps needed to store all
        # previous ones to ith index
        left[i] = left[i - 1] + count
 
        # Count number of 1s
        # present till i-th index
        count += A[i]
 
    # Initialize count
    count = A[n - 1]
 
    # Traverse the array in
    # backward direction
    for i in range(n - 2, -1, -1):
       
        # Steps needed to store all 1s to
        # the right of i at current index
        right[i] = right[i + 1] + count
 
        # Count number of 1s
        # present after i-th index
        count += A[i]
 
    # Prthe number of steps required
    for i in range(n):
        res[i] = left[i] + right[i]
        print(res[i], end = " ")
    print()
 
# Driver Code
if __name__ == '__main__':
    A = [1, 0, 1, 0]
    minsteps(A)
 
# This code is contributed by mohit kumar 29.


C#
// C# Program to implement
// the above approach
using System;
class GFG
{
   
  // Function to print minimum steps
  // required to shift all 1s to a
  // single index in a binary array
  static void minsteps(int[] A)
  {
 
    // Size of array
    int n = A.Length;
 
    // Used to store cummulative sum
    int[] left = new int [n];
    for (int i = 1; i < n; i++) {
      left[i] = 0;
    }
 
    int[] right = new int [n];
    for (int i = 1; i < n; i++) {
      right[i] = 0;
    }
 
    int[] res = new int [n];
    for (int i = 1; i < n; i++) {
      res[i] = 0;
    }
 
    // Initialize count
    int count = A[0];
 
    // Traverse the array in
    // forward direction
    for (int i = 1; i < n; i++) {
      // Steps needed to store all
      // previous ones to ith index
      left[i] = left[i - 1] + count;
 
      // Count number of 1s
      // present till i-th index
      count += A[i];
    }
 
    // Initialize count
    count = A[n - 1];
 
    // Traverse the array in
    // backward direction
    for (int i = n - 2; i >= 0; i--) {
      // Steps needed to store all 1s to
      // the right of i at current index
      right[i] = right[i + 1] + count;
 
      // Count number of 1s
      // present after i-th index
      count += A[i];
    }
 
    // Print the number of steps required
    for (int i = 0; i < n; i++) {
      res[i] = left[i] + right[i];
      Console.Write(res[i] + " ");
    }
    Console.WriteLine();
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int[] A = { 1, 0, 1, 0 };
    minsteps(A);
  }
}
 
// This code is contributed by susmitakundugoaldanga.


输出:
2 2 2 4

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