Python|尽量减少除以2的操作,使奇数和偶数交替的阵列

148 阅读2分钟

给出一个有N个 正整数的数组arr[]。任务是找出使数组包含交替出现的奇数和偶数所需的最少操作数。在一次操作中,任何数组元素都可以被其一半取代(即arr[i]/2)。

例子。

输入。 N=6, arr = [4, 10, 6, 6, 2, 7]
输出。 2
解释。 我们可以将索引1和3的元素
,得到数组[4, 5, 6, 3, 2, 7],这是不对等的。

**输入。**N=6, arr = [3, 10, 7, 18, 9, 66]
输出。 0
解释。 不需要任何操作,因为数组已经是备用的。

办法。 要解决这个问题,请使用以下方法。

尝试数组中以奇数和偶数开始的两种可能性,将两种可能性中的最小值作为答案打印出来。

请按照以下步骤来解决这个问题。

  • 声明并初始化两个变量result1result20
  • 遍历数组的所有索引,从0N-1
    • 如果偶数索引处的元素是奇数,那么
      • 用元素除以2,然后递增result1,直到它变成偶数。
    • 如果奇数索引处的元素是偶数,那么
      • 将元素除以2,然后将结果1递增,直到它变成奇数。
  • 0N-1的所有索引遍历数组。
    • 如果偶数索引处的元素是偶数,那么
      • 元素除以2,然后增加结果2,直到它变成奇数。
    • 如果奇数索引处的元素是奇数,那么
      • 元素除以2,然后增加结果2,直到它变成偶数。
  • 打印结果1结果2的最小值。

下面是上述方法的实现。

Python

# python3 code to implement the approach

# Function to find the minimum number of operations
def minOperations(arr, n):

    # Two variables to count number of operations
    result1 = 0
    result2 = 0

    # For array starting with even element
    for i in range(0, n):
        element = arr[i]

        # For even indices
        if (i % 2 == 0):

            # If element is already even
            if (element % 2 == 0):
                continue

            # Otherwise keep dividing by 2
            # till element becomes even
            else:
                while (element % 2 == 1):
                    element //= 2
                    result1 += 1

        # For odd indices
        else:

            # If element is already odd
            if (element % 2 == 1):
                continue

            # Otherwise keep dividing by 2
            # till element becomes odd
            else:
                while (element % 2 == 0):
                    element //= 2
                    result1 += 1

    # For array starting from odd element
    for i in range(0, n):
        element = arr[i]

        # For even indices
        if (i % 2 == 0):

            # If element is already odd
            if (element % 2 == 1):
                continue

            # Otherwise keep dividing by 2
            # till element becomes odd
            else:
                while (element % 2 == 0):
                    element //= 2
                    result2 += 1

        # For odd indices
        else:

            # If element is already even
            if (element % 2 == 0):
                continue

            # Otherwise keep dividing by 2
            # till element becomes even
            else:
                while (element % 2 == 1):
                    element //= 2
                    result2 += 1

    return min(result1, result2)

# Driver code
if __name__ == "__main__":

    N = 6
    arr = [4, 10, 6, 6, 2, 3]

    # Function call
    print(minOperations(arr, N))

    # This code is contributed by rakeshsahni

输出

2

时间复杂度。 O(N * log(max(arr[i]))), 其中max(arr[i])是数组中的最大元素。
辅助空间。 O(1)