给定一个由N个正整数组成的数组arr [] ,任务是根据每个元素的数字的GCD递增顺序对数组arr []进行排序。如果两个或多个元素的GCD相同,则根据它们的值进行排序。
例子:
Input: arr[] = {555, 363, 488, 244}
Output: 244 363 488 555
Explanation:
Following the GCD of the digits of each number:
- 555: GCD(5, 5, 5) = 5.
- 363: GCD(3, 6, 3) = 3.
- 488: GCD(4, 8, 8) = 4.
- 244: GCD(2, 4, 4) = 2.
After sorting according the given criteria, the order of elements are {244, 363, 488, 555}.
Input: arr[] = {555, 363, 488, 244, 444, 5}
Output: 244 363 444 488 5 555
方法:可以通过将比较器函数与sort()函数一起使用来解决给定的问题。比较器函数定义为:
- 它一次需要两个参数,如果第一个参数的GCD小于第二个参数,则返回true 。
- 如果GCD值相同,则如果第一个参数小于第二个参数,则它返回true 。否则,返回false 。
下面是上述方法的实现:
Python3
# Python program for the above approach
# Function to calculate
# GCD of two integers
def gcd(a, b):
# Base Case
if not b:
return a
# Recursively calculate GCD
return gcd(b, a % b)
# Function to calculate GCD
# of two array elements
def keyFunc(n):
getGCD = int(str(n)[0])
# Update the getGCD
for i in str(n):
getGCD = gcd(getGCD, int(i))
# Return the resultant GCD
return getGCD
# Function to sort an array by
# increasing order of GCD of
# digits of array elements
def sortArrayByGCD(arr):
# Sort the array
arr.sort()
# Sort the array according to gcd of
# digits using comparator function
arr = sorted(arr, key = keyFunc)
# Print the resultant array
print(*arr)
# Driver Code
# Given array
arr = [555, 363, 488, 244]
sortArrayByGCD(arr)
输出:
244 363 488 555
时间复杂度: O(N * log N)
辅助空间: O(1)