Diferencia mínima entre elementos adyacentes de una array que contienen elementos de cada fila de una array

Dada una array de N filas y M columnas, la tarea es encontrar la diferencia absoluta mínima entre cualquiera de los dos elementos adyacentes de una array de tamaño N , que se crea seleccionando un elemento de cada fila de la array. Tenga en cuenta que el elemento seleccionado de la fila 1 se convertirá en arr[0], el elemento seleccionado de la fila 2 se convertirá en arr[1] y así sucesivamente.

Ejemplos:  

Input :  N = 2, M = 2
m[2][2] = { 8, 2,
            6, 8 }
Output : 0.
Picking 8 from row 1 and picking 8 from row 2, we create an array { 8, 8 } and minimum
difference between any of adjacent element is 0.

Input :  N = 3, M = 3
m[3][3] = { 1, 2, 3
            4, 5, 6 
            7, 8, 9 }
Output : 1.

La idea es ordenar todas las filas individualmente y luego realizar una búsqueda binaria para encontrar el elemento más cercano en la siguiente fila para cada elemento. 

Para hacer esto de manera eficiente, ordene cada fila de la array. Comenzando desde la fila 1 hasta la fila N – 1 de la array, para cada elemento m[i][j] de la fila actual en la array, busque el elemento más pequeño en la siguiente fila que sea mayor o igual que el elemento actual, digamos p y el elemento más grande que es más pequeño que el elemento actual, digamos q. Esto se puede hacer usando la búsqueda binaria . Finalmente, encuentre el mínimo de la diferencia del elemento actual de p y q y actualice la variable.

A continuación se muestra la implementación de este enfoque: 

C++

// C++ program to find the minimum absolute difference
// between any of the adjacent elements of an array
// which is created by picking one element from each
// row of the matrix.
#include<bits/stdc++.h>
using namespace std;
#define R 2
#define C 2
 
// Return smallest element greater than or equal
// to the current element.
int bsearch(int low, int high, int n, int arr[])
{
    int mid = (low + high)/2;
 
    if(low <= high)
    {
        if(arr[mid] < n)
            return bsearch(mid +1, high, n, arr);
        return bsearch(low, mid - 1, n, arr);
    }
 
    return low;
}
 
// Return the minimum absolute difference adjacent
// elements of array
int mindiff(int arr[R][C], int n, int m)
{
    // Sort each row of the matrix.
    for (int i = 0; i < n; i++)
        sort(arr[i], arr[i] + m);
 
    int ans = INT_MAX;
 
    // For each matrix element
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = 0; j < m; j++)
        {
            // Search smallest element in the next row which
            // is greater than or equal to the current element
            int p = bsearch(0, m-1, arr[i][j], arr[i + 1]);
            ans = min(ans, abs(arr[i + 1][p] - arr[i][j]));
 
            // largest element which is smaller than the current
            // element in the next row must be just before
            // smallest element which is greater than or equal
            // to the current element because rows are sorted.
            if (p-1 >= 0)
                ans = min(ans, abs(arr[i + 1][p - 1] - arr[i][j]));
        }
    }
    return ans;
}
 
// Driven Program
int main()
{
    int m[R][C] =
    {
        8, 5,
        6, 8,
    };
 
    cout << mindiff(m, R, C) << endl;
    return 0;
}

Java

// Java program to find the minimum
// absolute difference between any
// of the adjacent elements of an
// array which is created by picking
// one element from each row of the matrix
import java.util.Arrays;
class GFG
{
static final int R=2;
static final int C=2;
 
// Return smallest element greater than
// or equal to the current element.
static int bsearch(int low, int high, int n, int arr[])
{
    int mid = (low + high)/2;
 
    if(low <= high)
    {
        if(arr[mid] < n)
            return bsearch(mid +1, high, n, arr);
        return bsearch(low, mid - 1, n, arr);
    }
 
    return low;
}
 
// Return the minimum absolute difference adjacent
// elements of array
static int mindiff(int arr[][], int n, int m)
{
 
    // Sort each row of the matrix.
    for (int i = 0; i < n; i++)
        Arrays.sort(arr[i]);
 
    int ans = +2147483647;
 
    // For each matrix element
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = 0; j < m; j++)
        {
 
        // Search smallest element in the
        // next row which is greater than
        // or equal to the current element
        int p = bsearch(0, m-1, arr[i][j], arr[i + 1]);
        ans = Math.min(ans, Math.abs(arr[i + 1][p] - arr[i][j]));
 
        // largest element which is smaller than the current
        // element in the next row must be just before
        // smallest element which is greater than or equal
        // to the current element because rows are sorted.
        if (p-1 >= 0)
            ans = Math.min(ans,
                        Math.abs(arr[i + 1][p - 1] - arr[i][j]));
        }
    }
    return ans;
}
 
    //Driver code
public static void main (String[] args)
{
    int m[][] ={{8, 5},
                {6, 8}};
 
    System.out.println(mindiff(m, R, C));
}
}
//This code is contributed by Anant Agarwal.

Python3

# Python program to find the minimum absolute difference
# between any of the adjacent elements of an array
# which is created by picking one element from each
# row of the matrix.
# R 2
# C 2
  
# Return smallest element greater than or equal
# to the current element.
def bsearch(low, high, n, arr):
    mid = (low + high)//2
  
    if(low <= high):
        if(arr[mid] < n):
            return bsearch(mid +1, high, n, arr);
        return bsearch(low, mid - 1, n, arr);
  
    return low;
  
# Return the minimum absolute difference adjacent
# elements of array
def mindiff(arr, n, m):
 
    # arr = [0 for i in range(R)][for j in range(C)]
    # Sort each row of the matrix.
    for i in range(n):
        sorted(arr)
  
    ans = 2147483647
  
    # For each matrix element
    for i in range(n-1):
        for j in range(m):
            # Search smallest element in the next row which
            # is greater than or equal to the current element
            p = bsearch(0, m-1, arr[i][j], arr[i + 1])
            ans = min(ans, abs(arr[i + 1][p] - arr[i][j]))
  
            # largest element which is smaller than the current
            # element in the next row must be just before
            # smallest element which is greater than or equal
            # to the current element because rows are sorted.
            if (p-1 >= 0):
                ans = min(ans, abs(arr[i + 1][p - 1] - arr[i][j]))
    return ans;
  
# Driver Program
m =[8, 5], [6, 8]
print (mindiff(m, 2, 2))
 
# This code is contributed by Afzal

C#

// C# program to find the minimum
// absolute difference between any
// of the adjacent elements of an
// array which is created by picking
// one element from each row of the matrix
using System;
 
class GFG
{
     
static public int R=2;
static public int C=2;
 
// Return smallest element greater than
// or equal to the current element.
static int bsearch(int low, int high, int n, int []arr)
{
    int mid = (low + high)/2;
 
    if(low <= high)
    {
        if(arr[mid] < n)
            return bsearch(mid +1, high, n, arr);
        return bsearch(low, mid - 1, n, arr);
    }
 
    return low;
}
public static int[] GetRow(int[,] matrix, int row)
{
    var rowLength = matrix.GetLength(1);
    var rowVector = new int[rowLength];
 
    for (var i = 0; i < rowLength; i++)
    rowVector[i] = matrix[row, i];
 
    return rowVector;
}
// Return the minimum absolute difference adjacent
// elements of array
static int mindiff(int [,]arr, int n, int m)
{
 
    // Sort each row of the matrix.
    for (int i = 0; i < n; i++)
        Array.Sort(GetRow(arr,i));
 
    int ans = +2147483647;
 
    // For each matrix element
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = 0; j < m; j++)
        {
 
        // Search smallest element in the
        // next row which is greater than
        // or equal to the current element
        int p = bsearch(0, m-1, arr[i,j], GetRow(arr,i+1));
        ans = Math.Min(ans, Math.Abs(arr[i + 1,p] - arr[i,j]));
 
        // largest element which is smaller than the current
        // element in the next row must be just before
        // smallest element which is greater than or equal
        // to the current element because rows are sorted.
        if (p-1 >= 0)
            ans = Math.Min(ans,
                        Math.Abs(arr[i + 1,p - 1] - arr[i,j]));
        }
    }
    return ans;
}
 
// Driver code
public static void Main (String[] args)
{
    int [,]m ={{8, 5},
                {6, 8}};
 
    Console.WriteLine(mindiff(m, R, C));
}
}
 
// This code is contributed by 29AjayKumar

PHP

<?php
// PHP program to find the minimum
// absolute difference between any
// of the adjacent elements of an
// array which is created by picking
// one element from each row of the matrix.
$R = 2;
$C = 2;
 
// Return smallest element greater
// than or equal to the current element.
function bsearch($low, $high, $n, $arr)
{
    $mid = ($low + $high) / 2;
 
    if($low <= $high)
    {
        if($arr[$mid] < $n)
            return bsearch($mid + 1, $high,
                                 $n, $arr);
        return bsearch($low, $mid - 1,
                            $n, $arr);
    }
    return $low;
}
 
// Return the minimum absolute difference
// adjacent elements of array
function mindiff($arr, $n, $m)
{
    // Sort each row of the matrix.
    for ($i = 0; $i < $n; $i++)
        sort($arr);
 
    $ans = PHP_INT_MAX;
 
    // For each matrix element
    for ($i = 0; $i < $n - 1; $i++)
    {
        for ( $j = 0; $j < $m; $j++)
        {
            // Search smallest element in the
            // next row which is greater than
            // or equal to the current element
            $p = bsearch(0, $m - 1, $arr[$i][$j],
                                    $arr[$i + 1]);
            $ans = min($ans, abs($arr[$i + 1][$p] -
                                 $arr[$i][$j]));
 
            // largest element which is smaller than
            // the current element in the next row
            // must be just before smallest element
            // which is greater than or equal to the
            // current element because rows are sorted.
            if ($p - 1 >= 0)
                $ans = min($ans, abs($arr[$i + 1][$p - 1] -
                                     $arr[$i][$j]));
        }
    }
    return $ans;
}
 
// Driver Code
$m = array(8, 5, 6, 8);
 
echo mindiff($m, $R, $C), "\n";
 
// This code is contributed by Sach_Code
?>

Javascript

<script>
 
// JavaScript program to find the minimum
// absolute difference between any
// of the adjacent elements of an
// array which is created by picking
// one element from each row of the matrix.
let R = 2;
let C = 2;
   
// Return smallest element greater than
// or equal to the current element.
function bsearch(low, high, n, arr)
{
    let mid = (low + high) / 2;
   
    if (low <= high)
    {
        if (arr[mid] < n)
            return bsearch(mid + 1,
                           high, n, arr);
             
        return bsearch(low, mid - 1,
                       n, arr);
    }
    return low;
}
   
// Return the minimum absolute difference
// adjacent elements of array
function mindiff(arr, n, m)
{
     
    // Sort each row of the matrix.
    for(let i = 0; i < n; i++)
        arr.sort();
   
    let ans = +2147483647;
   
    // For each matrix element
    for(let i = 0; i < n - 1; i++)
    {
        for(let j = 0; j < m; j++)
        {
             
            // Search smallest element in the
            // next row which is greater than
            // or equal to the current element
            let p = bsearch(0, m - 1, arr[i][j],
                                      arr[i + 1]);
            ans = Math.min(ans,
                  Math.abs(arr[i + 1][p] -
                           arr[i][j]));
       
            // largest element which is smaller
            // than the current element in the
            // next row must be just before smallest
            // element which is greater than or equal
            // to the current element because
            // rows are sorted.
            if (p - 1 >= 0)
                ans = Math.min(ans,
                      Math.abs(arr[i + 1][p - 1] -
                               arr[i][j]));
        }
    }
    return ans;
}
  
// Driver Code
let m = [ [ 8, 5 ],
          [ 6, 8 ] ];
 
document.write(mindiff(m, R, C));
 
// This code is contributed by code_hunt
 
</script>
Producción

0

Complejidad del tiempo: O(N*M*logM).

Este artículo es una contribución de Anuj Chauhan . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks. 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *