k-ésima diferencia absoluta más pequeña de dos elementos en una array

Nos dan una array de tamaño n que contiene números enteros positivos. La diferencia absoluta entre los valores de los índices i y j es |a[i] – a[j]|. Hay n*(n-1)/2 de tales pares y se nos pide imprimir el k-ésimo (1 <= k <= n*(n-1)/2) como la diferencia absoluta más pequeña entre todos estos pares.

Ejemplos: 

C++

// C++ program to find k-th absolute difference
// between two elements
#include<bits/stdc++.h>
using namespace std;
 
// returns number of pairs with absolute difference
// less than or equal to mid.
int countPairs(int *a, int n, int mid)
{
    int res = 0;
    for (int i = 0; i < n; ++i)
 
        // Upper bound returns pointer to position
        // of next higher number than a[i]+mid in
        // a[i..n-1]. We subtract (a + i + 1) from
        // this position to count
        res += upper_bound(a+i, a+n, a[i] + mid) -
                                    (a + i + 1);
    return res;
}
 
// Returns k-th absolute difference
int kthDiff(int a[], int n, int k)
{
    // Sort array
    sort(a, a+n);
 
    // Minimum absolute difference
    int low = a[1] - a[0];
    for (int i = 1; i <= n-2; ++i)
        low = min(low, a[i+1] - a[i]);
 
    // Maximum absolute difference
    int high = a[n-1] - a[0];
 
    // Do binary search for k-th absolute difference
    while (low < high)
    {
        int mid = (low+high)>>1;
        if (countPairs(a, n, mid) < k)
            low = mid + 1;
        else
            high = mid;
    }
 
    return low;
}
 
// Driver code
int main()
{
    int k = 3;
    int a[] = {1, 2, 3, 4};
    int n = sizeof(a)/sizeof(a[0]);
    cout << kthDiff(a, n, k);
    return 0;
}

Java

// Java program to find k-th absolute difference
// between two elements
import java.util.Scanner;
import java.util.Arrays;
 
class GFG
{
    // returns number of pairs with absolute
    // difference less than or equal to mid
    static int countPairs(int[] a, int n, int mid)
    {
        int res = 0, value;
        for(int i = 0; i < n; i++)
        {
            // Upper bound returns pointer to position
            // of next higher number than a[i]+mid in
            // a[i..n-1]. We subtract (ub + i + 1) from
            // this position to count
            if(a[i]+mid>a[n-1])
              res+=(n-(i+1));
            else
            {
             int ub = upperbound(a, n, a[i]+mid);
             res += (ub- (i+1));
            }
        }
        return res;
    }
 
    // returns the upper bound
    static int upperbound(int a[], int n, int value)
    {
        int low = 0;
        int high = n;
        while(low < high)
        {
            final int mid = (low + high)/2;
            if(value >= a[mid])
                low = mid + 1;
            else
                high = mid;
        }
 
    return low;
    }
 
    // Returns k-th absolute difference
    static int kthDiff(int a[], int n, int k)
    {
        // Sort array
        Arrays.sort(a);
 
        // Minimum absolute difference
        int low = a[1] - a[0];
        for (int i = 1; i <= n-2; ++i)
            low = Math.min(low, a[i+1] - a[i]);
 
        // Maximum absolute difference
        int high = a[n-1] - a[0];
 
        // Do binary search for k-th absolute difference
        while (low < high)
        {
            int mid = (low + high) >> 1;
            if (countPairs(a, n, mid) < k)
                low = mid + 1;
            else
                high = mid;
        }
 
        return low;
    }
 
    // Driver function to check the above functions
    public static void main(String args[])
    {
        Scanner s = new Scanner(System.in);
        int k = 3;
        int a[] = {1,2,3,4};
        int n = a.length;
        System.out.println(kthDiff(a, n, k));
    }
 
}
// This code is contributed by nishkarsh146

Python3

# Python3 program to find
# k-th absolute difference
# between two elements
from bisect import bisect as upper_bound
 
# returns number of pairs with
# absolute difference less than
# or equal to mid.
def countPairs(a, n, mid):
    res = 0
    for i in range(n):
 
        # Upper bound returns pointer to position
        # of next higher number than a[i]+mid in
        # a[i..n-1]. We subtract (a + i + 1) from
        # this position to count
        res += upper_bound(a, a[i] + mid)
    return res
 
# Returns k-th absolute difference
def kthDiff(a, n, k):
     
    # Sort array
    a = sorted(a)
 
    # Minimum absolute difference
    low = a[1] - a[0]
    for i in range(1, n - 1):
        low = min(low, a[i + 1] - a[i])
 
    # Maximum absolute difference
    high = a[n - 1] - a[0]
 
    # Do binary search for k-th absolute difference
    while (low < high):
        mid = (low + high) >> 1
        if (countPairs(a, n, mid) < k):
            low = mid + 1
        else:
            high = mid
 
    return low
 
# Driver code
k = 3
a = [1, 2, 3, 4]
n = len(a)
print(kthDiff(a, n, k))
 
# This code is contributed by Mohit Kumar

C#

// C# program to find k-th
// absolute difference
// between two elements
using System;
class GFG{
    
// returns number of pairs
// with absolute difference
// less than or equal to mid
static int countPairs(int[] a,
                      int n,
                      int mid)
{
  int res = 0;
  for(int i = 0; i < n; i++)
  {
    // Upper bound returns pointer
    // to position of next higher
    // number than a[i]+mid in
    // a[i..n-1]. We subtract
    // (ub + i + 1) from
    // this position to count
    int ub = upperbound(a, n,
                        a[i] + mid);
    res += (ub - (i));
  }
  return res;
}
 
// returns the upper bound
static int upperbound(int []a,
                      int n,
                      int value)
{
  int low = 0;
  int high = n;
  while(low < high)
  {
    int mid = (low + high)/2;
    if(value >= a[mid])
      low = mid + 1;
    else
      high = mid;
  }
 
  return low;
}
 
// Returns k-th absolute
// difference
static int kthDiff(int []a,
                   int n, int k)
{
  // Sort array
  Array.Sort(a);
 
  // Minimum absolute
  // difference
  int low = a[1] - a[0];
  for (int i = 1; i <= n - 2; ++i)
    low = Math.Min(low, a[i + 1] -
                   a[i]);
 
  // Maximum absolute
  // difference
  int high = a[n - 1] - a[0];
 
  // Do binary search for
  // k-th absolute difference
  while (low < high)
  {
    int mid = (low + high) >> 1;
    if (countPairs(a, n, mid) < k)
      low = mid + 1;
    else
      high = mid;
  }
 
  return low;
}
 
// Driver code
public static void Main(String []args)
{
  int k = 3;
  int []a = {1, 2, 3, 4};
  int n = a.Length;
  Console.WriteLine(kthDiff(a, n, k));
}
}
 
// This code is contributed by gauravrajput1

Javascript

<script>
 
// JavaScript program to find k-th
// absolute difference
// between two elements
 
 
// returns number of pairs
// with absolute difference
// less than or equal to mid
function countPairs(a, n, mid) {
    let res = 0;
    for (let i = 0; i < n; i++) {
        // Upper bound returns pointer
        // to position of next higher
        // number than a[i]+mid in
        // a[i..n-1]. We subtract
        // (ub + i + 1) from
        // this position to count
        let ub = upperbound(a, n,
            a[i] + mid);
        res += (ub - (i));
    }
    return res;
}
 
// returns the upper bound
function upperbound(a, n, value) {
    let low = 0;
    let high = n;
    while (low < high) {
        let mid = (low + high) / 2;
        if (value >= a[mid])
            low = mid + 1;
        else
            high = mid;
    }
 
    return low;
}
 
// Returns k-th absolute
// difference
function kthDiff(a, n, k) {
    // Sort array
    a.sort((a, b) => a - b);
 
    // Minimum absolute
    // difference
    let low = a[1] - a[0];
    for (let i = 1; i <= n - 2; ++i)
        low = Math.min(low, a[i + 1] -
            a[i]);
 
    // Maximum absolute
    // difference
    let high = a[n - 1] - a[0];
 
    // Do binary search for
    // k-th absolute difference
    while (low < high) {
        let mid = (low + high) >> 1;
        if (countPairs(a, n, mid) < k)
            low = mid + 1;
        else
            high = mid;
    }
 
    return low;
}
 
// Driver code
 
let k = 3;
let a = [1, 2, 3, 4];
let n = a.length;
document.write(kthDiff(a, n, k));
 
 
 
// This code is contributed by gfgking
 
</script>

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 *