找到具有最大汉明距离的旋转
给定一个包含 n 个元素的数组,创建一个新数组,它是给定数组的旋转并且两个数组之间的汉明距离最大。
两个相等长度的数组或字符串之间的汉明距离是对应字符(元素)不同的位置数。
注意:给定输入可以有多个输出。
例子:
Input : 1 4 1
Output : 2
Explanation:
Maximum hamming distance = 2.
We get this hamming distance with 4 1 1
or 1 1 4
Input : N = 4
2 4 8 0
Output : 4
Explanation:
Maximum hamming distance = 4
We get this hamming distance with 4 8 0 2.
All the places can be occupied by another digit.
Other possible solutions are 8 0 2 4 and 0 2 4 8.
方法#1:
创建另一个数组,它的大小是原始数组的两倍,这样这个新数组(复制数组)的元素就是原始数组中以相同顺序重复两次的元素。例如,如果原始数组是 1 4 1,那么复制数组是 1 4 1 1 4 1。
现在,遍历复制数组并找到每次移位(或旋转)的汉明距离。所以我们检查 4 1 1, 1 1 4, 1 4 1,选择汉明距离最大的输出。
以下是上述方法的实现:
C++
// C++ program to Find another array
// such that the hamming distance
// from the original array is maximum
#include
using namespace std;
// Return the maximum hamming distance of a rotation
int maxHamming(int arr[], int n)
{
// arr[] to brr[] two times so that
// we can traverse through all rotations.
int brr[2 *n + 1];
for (int i = 0; i < n; i++)
brr[i] = arr[i];
for (int i = 0; i < n; i++)
brr[n+i] = arr[i];
// We know hamming distance with 0 rotation
// would be 0.
int maxHam = 0;
// We try other rotations one by one and compute
// Hamming distance of every rotation
for (int i = 1; i < n; i++)
{
int currHam = 0;
for (int j = i, k=0; j < (i + n); j++,k++)
if (brr[j] != arr[k])
currHam++;
// We can never get more than n.
if (currHam == n)
return n;
maxHam = max(maxHam, currHam);
}
return maxHam;
}
// driver program
int main()
{
int arr[] = {2, 4, 6, 8};
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxHamming(arr, n);
return 0;
}
Java
// Java program to Find another array
// such that the hamming distance
// from the original array is maximum
class GFG
{
// Return the maximum hamming
// distance of a rotation
static int maxHamming(int arr[], int n)
{
// arr[] to brr[] two times so that
// we can traverse through all rotations.
int brr[]=new int[2 *n + 1];
for (int i = 0; i < n; i++)
brr[i] = arr[i];
for (int i = 0; i < n; i++)
brr[n+i] = arr[i];
// We know hamming distance with
// 0 rotation would be 0.
int maxHam = 0;
// We try other rotations one by one
// and compute Hamming distance
// of every rotation
for (int i = 1; i < n; i++)
{
int currHam = 0;
for (int j = i, k=0; j < (i + n); j++,
k++)
if (brr[j] != arr[k])
currHam++;
// We can never get more than n.
if (currHam == n)
return n;
maxHam = Math.max(maxHam, currHam);
}
return maxHam;
}
// driver code
public static void main (String[] args)
{
int arr[] = {2, 4, 6, 8};
int n = arr.length;
System.out.print(maxHamming(arr, n));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python3 code to Find another array
# such that the hamming distance
# from the original array is maximum
# Return the maximum hamming
# distance of a rotation
def maxHamming( arr , n ):
# arr[] to brr[] two times so
# that we can traverse through
# all rotations.
brr = [0] * (2 * n + 1)
for i in range(n):
brr[i] = arr[i]
for i in range(n):
brr[n+i] = arr[i]
# We know hamming distance
# with 0 rotation would be 0.
maxHam = 0
# We try other rotations one by
# one and compute Hamming
# distance of every rotation
for i in range(1, n):
currHam = 0
k = 0
for j in range(i, i + n):
if brr[j] != arr[k]:
currHam += 1
k = k + 1
# We can never get more than n.
if currHam == n:
return n
maxHam = max(maxHam, currHam)
return maxHam
# driver program
arr = [2, 4, 6, 8]
n = len(arr)
print(maxHamming(arr, n))
# This code is contributed by "Sharad_Bhardwaj".
C#
// C# program to Find another array
// such that the hamming distance
// from the original array is maximum
using System;
class GFG {
// Return the maximum hamming
// distance of a rotation
static int maxHamming(int []arr, int n)
{
// arr[] to brr[] two times so that
// we can traverse through all rotations.
int []brr=new int[2 * n + 1];
for (int i = 0; i < n; i++)
brr[i] = arr[i];
for (int i = 0; i < n; i++)
brr[n+i] = arr[i];
// We know hamming distance with
// 0 rotation would be 0.
int maxHam = 0;
// We try other rotations one by one
// and compute Hamming distance
// of every rotation
for (int i = 1; i < n; i++)
{
int currHam = 0;
for (int j = i, k=0; j < (i + n);
j++, k++)
if (brr[j] != arr[k])
currHam++;
// We can never get more than n.
if (currHam == n)
return n;
maxHam = Math.Max(maxHam, currHam);
}
return maxHam;
}
// driver code
public static void Main ()
{
int []arr = {2, 4, 6, 8};
int n = arr.Length;
Console.Write(maxHamming(arr, n));
}
}
// This code is contributed by vt_m.
PHP
Javascript
Python3
# Python code to to find maximum
# of an array with it's rotations
import time
# Function hamming distance to find
# the hamming distance for two lists/strings
def hamming_distance(x: list, y: list):
# Initialize count
count = 0
# Run loop for size of x(or y)
# as both as same length
for i in range(len(x)):
# Check if corresponding elements
# at same index are not equal
if(x[i] != y[i]):
# Increment the count every
# time above condition satisfies
count += 1
# Return the hamming distance
# for given pair of lists or strings
return count
# Function to rotate the given array
# in anti-clockwise direction by 1
def rotate_by_one(arr: list):
# Store 1st element in a variable
x = arr[0]
# Update each ith element (0<=i<=n-2)
# with it's next value
for i in range(0, len(arr)-1):
arr[i] = arr[i+1]
# Assign 1st element to the last index
arr[len(arr)-1] = x
# Function max_hamming_distance to find
# the maximum hamming distance for given array
def max_hamming_distance(arr: list):
# Initialize a variable to store
# maximum hamming distance
max_h = -10000000000
# Store size of the given array
# in a variable n
n = len(arr)
# Initialize a new array
a = []
# Copy the original array in new array
for i in range(n):
a.append(arr[i])
# Run loop for i=0 to i=n-1 for n-1 rotations
for i in range(1, n):
# Find the next rotation
rotate_by_one(arr)
print("Array after %d rotation : " % (i), arr)
# Store hamming distance of current
# rotation with original array
curr_h_dist = hamming_distance(a, arr)
print("Hamming Distance with %d rotations: %d" %
(i, curr_h_dist))
# Check if current hamming distance
# is greater than max hamming distance
if curr_h_dist > max_h:
# If yes, assign value of current
# hamming distance to max hamming distance
max_h = curr_h_dist
print('\n')
# Return maximum hamming distance
return max_h
# Driver code
if __name__ == '__main__':
arr = [3, 0, 6, 4, 3]
start = time.time()
print('\n')
print("Original Array : ", arr)
print('\n')
print("Maximum Hamming Distance: ", max_hamming_distance(arr))
end = time.time()
print(f"Execution Time = {end - start}")
# This code is contributed by Vivek_Kumar_Sinha
输出:
4
时间复杂度:O(n*n)
方法#2:
我们可以利用Python中的列表理解,使用不同的方法找到最大汉明距离。在这种方法中,我们将工作划分为 3 个独立的功能。
- hamming_distance(x : list, y : list):此方法返回作为参数传递的两个列表的汉明距离。这个想法是计算两个列表 x 和 y 中相同索引处元素不同的位置,其中 x 是输入中的原始数组,y 是其中一个旋转。从 0 开始初始化变量计数。从起始索引 0 到最后一个索引 (n-1) 运行循环,其中 n 是列表的长度。对于每次迭代,检查 x 的元素和索引 i (0<=i<=n-1) 处的元素是否相同。如果它们相同,则增加计数器。循环完成后,返回计数(根据定义,这是给定数组或字符串的汉明距离)
- rotate_by_one(arr : list):此方法将数组(传入参数)逆时针旋转 1 个位置。例如,如果数组 [1,1,4,4] 被传递,此方法返回 [1,4,4,5,1]。这个想法是复制数组的第一个元素并将其保存在一个变量中(比如 x)。然后将数组从 0 迭代到 n-2 并在第 i 个位置复制每个第 i+1 个值。现在将 x 分配给最后一个索引。
- max_hamming_distance(arr : list):此方法找到给定数组的最大汉明距离及其旋转。请按照此方法中的以下步骤操作。我们将这个数组复制到一个新数组(比如 a)中并初始化一个变量 max。现在,在每 n 次旋转之后,我们得到原始数组。所以我们需要找到原始数组的汉明距离,它是 n-1 次旋转,并将当前最大值存储在一个变量中(比如最大值)。运行 n-1 次迭代的循环。对于每次迭代,我们遵循以下步骤:
- 通过调用方法 'rotate_by_one' 获取 arr 的下一个旋转。
- 调用方法 hamming distance() 并传递原始数组 (a) 和 a (arr) 的当前旋转并将返回的当前 hamming 距离存储在变量中(例如 curr_h_dist)。
- 检查 curr_h_dist 的值是否大于 max 的值。如果是,则将 curr_h_dist 的值分配给 max_h。
- 重复步骤 1-3 直到循环终止。
- 返回最大汉明距离(max_h)
Python3
# Python code to to find maximum
# of an array with it's rotations
import time
# Function hamming distance to find
# the hamming distance for two lists/strings
def hamming_distance(x: list, y: list):
# Initialize count
count = 0
# Run loop for size of x(or y)
# as both as same length
for i in range(len(x)):
# Check if corresponding elements
# at same index are not equal
if(x[i] != y[i]):
# Increment the count every
# time above condition satisfies
count += 1
# Return the hamming distance
# for given pair of lists or strings
return count
# Function to rotate the given array
# in anti-clockwise direction by 1
def rotate_by_one(arr: list):
# Store 1st element in a variable
x = arr[0]
# Update each ith element (0<=i<=n-2)
# with it's next value
for i in range(0, len(arr)-1):
arr[i] = arr[i+1]
# Assign 1st element to the last index
arr[len(arr)-1] = x
# Function max_hamming_distance to find
# the maximum hamming distance for given array
def max_hamming_distance(arr: list):
# Initialize a variable to store
# maximum hamming distance
max_h = -10000000000
# Store size of the given array
# in a variable n
n = len(arr)
# Initialize a new array
a = []
# Copy the original array in new array
for i in range(n):
a.append(arr[i])
# Run loop for i=0 to i=n-1 for n-1 rotations
for i in range(1, n):
# Find the next rotation
rotate_by_one(arr)
print("Array after %d rotation : " % (i), arr)
# Store hamming distance of current
# rotation with original array
curr_h_dist = hamming_distance(a, arr)
print("Hamming Distance with %d rotations: %d" %
(i, curr_h_dist))
# Check if current hamming distance
# is greater than max hamming distance
if curr_h_dist > max_h:
# If yes, assign value of current
# hamming distance to max hamming distance
max_h = curr_h_dist
print('\n')
# Return maximum hamming distance
return max_h
# Driver code
if __name__ == '__main__':
arr = [3, 0, 6, 4, 3]
start = time.time()
print('\n')
print("Original Array : ", arr)
print('\n')
print("Maximum Hamming Distance: ", max_hamming_distance(arr))
end = time.time()
print(f"Execution Time = {end - start}")
# This code is contributed by Vivek_Kumar_Sinha
输出
Original Array : [3, 0, 6, 4, 3]
Array after 1 rotation : [0, 6, 4, 3, 3]
Hamming Distance with 1 rotations: 4
Array after 2 rotation : [6, 4, 3, 3, 0]
Hamming Distance with 2 rotations: 5
Array after 3 rotation : [4, 3, 3, 0, 6]
Hamming Distance with 3 rotations: 5
Array after 4 rotation : [3, 3, 0, 6, 4]
Hamming Distance with 4 rotations: 4
Maximum Hamming Distance: 5
Execution Time = 5.0067901611328125e-05