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

📅  最后修改于: 2021-10-25 08:12:59             🧑  作者: Mango

给定一个大小为N的二进制数组A[] ,其中所有1都可以移动到其相邻位置,任务是打印大小为N的数组res[] ,其中res[i]包含所需的最少步骤数移动第i索引处的所有1

例子:

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

  1. 遍历数组。
  2. 对于每个i索引,计算将所有1移动到第i索引所需的步骤数。
  3. 迭代范围[0, N – 1] ,使用一个变量,比如i。
    • 初始化步骤 = 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的数量
  4. 初始化一个数组,比如right[],并初始化count = A[N – 1]。
  5. 迭代范围[N – 2, 0] ,并更新right[i] = right[i + 1] + count ,其中counti右侧1的数量
  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 print minimum 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]
 
    # Print the 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.


Javascript


输出:
2 2 2 4

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程