📜  数组中的最小反相因子

📅  最后修改于: 2022-05-13 01:57:49.656000             🧑  作者: Mango

数组中的最小反相因子

给定一个由 n 个正整数组成的数组,任务是找到给定数组中的最小反相因子。
反转因子定义为任意两个数字 arr i和 arr j的倒数之间的绝对差,其中 i != j。
注意:反转数字时应忽略尾随零,即反转时 1200 变为 21。
例子:

推荐:请先在“练习”上解决,然后再继续解决。

一种天真的方法是遍历两个循环以找到所有可能的对。分别反转两个数字并找到它们的绝对差。在每一步更新反相因子(最小绝对差)。时间复杂度为 O(N 2 )。
一种有效的方法是预先计算每个数组元素的反转并仅以反转形式存储它(也考虑尾随零的情况)。现在,要找到最小反相因子,请按非递减顺序对数组进行排序。由于数组已排序,因此任何两个相邻数字之间总是出现最小绝对差。
下面是上述方法的实现。

C++
// C++ implementation of the above approach
 
#include 
using namespace std;
 
// Function to find the minimum inverting factor
int findMinimumInvertingFactor(int arr[], int N)
{
    // ans stores the minimum inverting factor
    int ans = INT_MAX;
 
    // Iterate over the loop and convert each
    // array element into its reversed form
    for (int i = 0; i < N; i++) {
        string s;
        int num = arr[i];
 
        // Extract each digit of the number and
        // store it in reverse order
        while (num > 0) {
            s.push_back(num % 10 + '0');
            num /= 10;
        }
 
        // Find the position upto which trailing
        // zeroes occur
        int pos;
        for (pos = 0; pos < s.size(); pos++)
            if (s[pos] != 0)
                break;
 
        // Form the reversed number
        num = 0;
        for (int j = pos; j < s.size(); j++)
            num = num * 10 + (s[j] - '0');
        arr[i] = num;
    }
    sort(arr, arr + N);
 
    // Consider all adjacent pairs and update the
    // answer accordingly
    for (int i = 1; i < N; i++)
        ans = min(ans, abs(arr[i] - arr[i - 1]));
 
    return ans;
}
 
// Driver Code
int main()
{
    int arr[] = { 56, 20, 47, 93, 45 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << findMinimumInvertingFactor(arr, N) << endl;
    return 0;
}


Java
// Java implementation of the above approach
import java.util.*;
 
class GFG
{
     
// Function to find the minimum inverting factor
static int findMinimumInvertingFactor(int arr[], int N)
{
    // ans stores the minimum inverting factor
    int ans = Integer.MAX_VALUE;
 
    // Iterate over the loop and convert each
    // array element into its reversed form
    for (int i = 0; i < N; i++)
    {
        String s = "";
        int num = arr[i];
 
        // Extract each digit of the number and
        // store it in reverse order
        while (num > 0)
        {
            s+=(char)((num % 10) + '0');
            num /= 10;
        }
 
        // Find the position upto which trailing
        // zeroes occur
        int pos;
        for (pos = 0; pos < s.length(); pos++)
            if (s.charAt(pos) != 0)
                break;
 
        // Form the reversed number
        num = 0;
        for (int j = pos; j < s.length(); j++)
            num = num * 10 + (s.charAt(j) - '0');
        arr[i] = num;
    }
    Arrays.sort(arr);
 
    // Consider all adjacent pairs and update the
    // answer accordingly
    for (int i = 1; i < N; i++)
        ans = Math.min(ans, Math.abs(arr[i] - arr[i - 1]));
 
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 56, 20, 47, 93, 45 };
    int N = arr.length;
 
    System.out.println(findMinimumInvertingFactor(arr, N));
}
}
 
// This code contributed by Rajput-Ji


Python3
# Python3 implementation of the above approach
 
import sys
 
# Function to find the minimum inverting factor
def findMinimumInvertingFactor(arr, N) :
     
    # ans stores the minimum inverting factor
    ans = sys.maxsize
 
    # Iterate over the loop and convert each
    # array element into its reversed form
    for i in range(N) :
        num = arr[i]
        s = ""
 
        # Extract each digit of the number and
        # store it in reverse order
        while (num > 0) :
            s += str(num % 10)
            num //= 10
          
 
        # Find the position upto which trailing
        # zeroes occur
        for pos in range(len(s)) :
            if (s[pos] != "0") :
                break;
 
        # Form the reversed number
        num = 0
        for j in range(pos, len(s)) :
            num = num * 10 + (ord(s[j]) - ord("0"))
        arr[i] = num
      
    arr.sort()
    # Consider all adjacent pairs and update the
    # answer accordingly
    for i in range(N) :
        ans = min(ans, abs(arr[i] - arr[i - 1]))
 
    return ans
  
 
# Driver Code
if __name__ == "__main__" :
 
    arr= [ 56, 20, 47, 93, 45 ]
    N = len(arr)
     
    print(findMinimumInvertingFactor(arr, N))
 
# This code is contributed by Ryuga


C#
// C# implementation of the approach
using System;
 
class GFG
{
     
// Function to find the minimum inverting factor
static int findMinimumInvertingFactor(int []arr, int N)
{
    // ans stores the minimum inverting factor
    int ans = int.MaxValue;
 
    // Iterate over the loop and convert each
    // array element into its reversed form
    for (int i = 0; i < N; i++)
    {
        String s = "";
        int num = arr[i];
 
        // Extract each digit of the number and
        // store it in reverse order
        while (num > 0)
        {
            s+=(char)((num % 10) + '0');
            num /= 10;
        }
 
        // Find the position upto which trailing
        // zeroes occur
        int pos;
        for (pos = 0; pos < s.Length;pos++)
            if (s[pos] != 0)
                break;
 
        // Form the reversed number
        num = 0;
        for (int j = pos; j < s.Length; j++)
            num = num * 10 + (s[j] - '0');
        arr[i] = num;
    }
    Array.Sort(arr);
 
    // Consider all adjacent pairs and update the
    // answer accordingly
    for (int i = 1; i < N; i++)
        ans = Math.Min(ans, Math.Abs(arr[i] - arr[i - 1]));
 
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 56, 20, 47, 93, 45 };
    int N = arr.Length;
 
    Console.WriteLine(findMinimumInvertingFactor(arr, N));
}
}
 
/* This code contributed by PrinciRaj1992 */


PHP
 0)
        {
            $s.=chr($num % 10 + ord('0'));
            $num =(int)($num/10);
        }
 
        // Find the position upto which trailing
        // zeroes occur
        for ($pos = 0; $pos < strlen($s); $pos++)
            if ($s[$pos] != 0)
                break;
 
        // Form the reversed number
        $num = 0;
        for ($j = $pos; $j < strlen($s); $j++)
            $num = $num * 10 + (ord($s[$j]) - ord('0'));
        $arr[$i] = $num;
    }
    sort($arr);
 
    // Consider all adjacent pairs and update the
    // answer accordingly
    for ($i = 1; $i < $N; $i++)
        $ans = min($ans, abs($arr[$i] - $arr[$i - 1]));
 
    return $ans;
}
 
// Driver Code
 
$arr = array( 56, 20, 47, 93, 45 );
$N = count($arr);
 
echo findMinimumInvertingFactor($arr, $N)."\n";
 
// This code is contributed by mits
?>


Javascript


输出:
9

时间复杂度:O(N * logN)