📌  相关文章
📜  根据与给定值的绝对差对数组进行排序

📅  最后修改于: 2021-10-28 01:32:30             🧑  作者: Mango

给定一个n个不同元素的数组和一个数字x,按照与x的绝对差来排列数组元素,即差值最小的元素排在最前面,以此类推。
注意:如果两个或多个元素的距离相等,则按照给定数组中的相同顺序排列它们。
例子 :

Input : arr[] : x = 7, arr[] = {10, 5, 3, 9, 2}
Output : arr[] = {5, 9, 10, 3, 2}
Explanation:
7 - 10 = 3(abs)
7 - 5 = 2
7 - 3 = 4 
7 - 9 = 2(abs)
7 - 2 = 5
So according to the difference with X, 
elements are arranged as 5, 9, 10, 3, 2.

Input : x = 6, arr[] = {1, 2, 3, 4, 5}   
Output :  arr[] = {5, 4, 3, 2, 1}

Input : x = 5, arr[] = {2, 6, 8, 3}   
Output :  arr[] = {6, 3, 2, 8}

这个想法是使用自平衡二叉搜索树。我们遍历输入数组,对于每个元素,我们找到它与 x 的差异,并将差异存储为自平衡二叉搜索树中的键和元素作为值。最后,我们遍历树并打印它的中序遍历,这是所需的输出。
C++ 实现:
在 C++ 中,自平衡二进制搜索树由 set、map 和 multimap 实现。我们不能在这里使用 set 因为我们有键值对(不仅是键)。我们也不能直接使用 map ,因为单个键可以属于多个值,而 map 允许一个键使用单个值。所以我们使用 multimap 来存储键值对,并且一个键可以有多个值。

  1. 将值存储在多映射中,以 X 为键。
  2. 在 multimap 中,值将已经根据键排序,即与 X 的差异,因为它在内部实现了自平衡二进制搜索树。
  3. 使用映射的值更新数组的所有值,以便数组具有所需的输出。
C++
// C++ program to sort an array according absolute
// difference with x.
#include
using namespace std;
 
// Function to sort an array according absolute
// difference with x.
void rearrange(int arr[], int n, int x)
{
    multimap m;
    multimap:: iterator it;
    // Store values in a map with the difference
    // with X as key
    for (int i = 0 ; i < n; i++)
        m.insert(make_pair(abs(x-arr[i]),arr[i]));
 
    // Update the values of array
    int i = 0;
    for (it = m.begin(); it != m.end(); it++)
        arr[i++] = (*it).second ;
}
 
// Function to print the array
void printArray(int arr[] , int n)
{
    for (int i = 0 ; i < n; i++)
        cout << arr[i] << " ";
}
 
// Driver code
int main()
{
    int arr[] = {10, 5, 3, 9 ,2};
    int n = sizeof(arr)/sizeof(arr[0]);
    int x = 7;
    rearrange(arr, n, x);
    printArray(arr, n);
    return 0;
}


Java
// Java program to sort an array according absolute
// difference with x.
import java.io.*;
import java.util.*;
 
class GFG
{
 
    // Function to sort an array according absolute
    // difference with x.
    static void rearrange(int[] arr, int n, int x)
    {
            TreeMap> m =
                                    new TreeMap<>();
             
            // Store values in a map with the difference
            // with X as key
            for (int i = 0; i < n; i++)
            {
                int diff = Math.abs(x - arr[i]);
                if (m.containsKey(diff))
                {
                    ArrayList al = m.get(diff);
                    al.add(arr[i]);
                    m.put(diff, al);
                }
                else
                {
                        ArrayList al = new
                                       ArrayList<>();
                        al.add(arr[i]);
                        m.put(diff,al);
                }
            }
 
            // Update the values of array
            int index = 0;
            for (Map.Entry entry : m.entrySet())
            {
                ArrayList al = m.get(entry.getKey());
                for (int i = 0; i < al.size(); i++)
                        arr[index++] = al.get(i);
            }
    }
 
    // Function to print the array
    static void printArray(int[] arr, int n)
    {
            for (int i = 0; i < n; i++)
                System.out.print(arr[i] + " ");
    }
 
    // Driver code
    public static void main(String args[])
    {
            int[] arr = {10, 5, 3, 9 ,2};
            int n = arr.length;
            int x = 7;
            rearrange(arr, n, x);
            printArray(arr, n);
    }
}
 
// This code is contributed by rachana soma


Python3
# Python3 program to sort an
# array according absolute
# difference with x.
 
# Function to sort an array
# according absolute difference
# with x.
def rearrange(arr, n, x):
 
    m = {}
 
    # Store values in a map
    # with the difference
    # with X as key
    for i in range(n):
        m[arr[i]] = abs(x - arr[i])
 
    m = {k : v for k, v in sorted(m.items(),
         key = lambda item : item[1])}
 
    # Update the values of array
    i = 0
 
    for it in m.keys():
        arr[i] = it
        i += 1
 
# Function to print the array
def printArray(arr, n):
 
    for i in range(n):
        print(arr[i], end = " ")
         
# Driver code
if __name__ == "__main__":
 
    arr = [10, 5, 3, 9, 2]
    n = len(arr)
    x = 7
    rearrange(arr, n, x)
    printArray(arr, n)
 
# This code is contributed by Chitranayal


C#
// C# program to sort an array according absolute
// difference with x.
using System;
using System.Collections.Generic;
 
public class GFG
{
 
  // Function to sort an array according absolute
  // difference with x.
  static void rearrange(int[] arr, int n, int x)
  {
    SortedDictionary> m = new SortedDictionary>();
 
    // Store values in a map with the difference
    // with X as key
    for (int i = 0; i < n; i++)
    {
      int diff = Math.Abs(x - arr[i]);
      if (m.ContainsKey(diff))
      {
        List al = m;
        al.Add(arr[i]);
        m = al;
      }
      else
      {
        List al = new  List();
        al.Add(arr[i]);
        m.Add(diff, al);
      }
    }
    // Update the values of array
    int index = 0;
    foreach(int entry in m.Keys)
    {
      List al = m[entry];
      for (int i = 0; i < al.Count; i++)
        arr[index++] = al[i];
    }
  }
 
  // Function to print the array
  static void printArray(int[] arr, int n)
  {
    for (int i = 0; i < n; i++)
      Console.Write(arr[i] + " ");
  }
 
  // Driver code
  static public void Main (){
    int[] arr = {10, 5, 3, 9 ,2};
    int n = arr.Length;
    int x = 7;
    rearrange(arr, n, x);
    printArray(arr, n);
  }
}
 
// This code is contributed by avanitrachhadiya2155


Javascript


C++
// CPP program for the above approach
#include 
using namespace std;
 
void rearrange(int arr[], int n, int x)
{
    /*
        We can send the value x into
        lambda expression as
        follows: [capture]()
        {
            //statements
            //capture value can be used inside
        }
    */
    stable_sort(arr, arr + n, [x](int a, int b)
    {
        if (abs(a - x) < abs(b - x))
            return true;
        else
            return false;
    });
}
 
// Driver code
int main()
{
    int arr[] = { 10, 5, 3, 9, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 7;
    rearrange(arr, n, x);
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}


输出
5 9 10 3 2 

基于 C++ STL 的实现:在 C++ 中,我们可以使用 stable_sort(),并为自定义比较器函数编写一个 lambda 表达式。这个解决方案很优雅,也更容易理解。编写 lambda 表达式的唯一挑战是将值 ‘x’ 发送到 lambda 表达式中,以便能够在表达式中使用它。这可以通过在类的帮助下重载运算符或使用更简单的捕获来实现。

C++

// CPP program for the above approach
#include 
using namespace std;
 
void rearrange(int arr[], int n, int x)
{
    /*
        We can send the value x into
        lambda expression as
        follows: [capture]()
        {
            //statements
            //capture value can be used inside
        }
    */
    stable_sort(arr, arr + n, [x](int a, int b)
    {
        if (abs(a - x) < abs(b - x))
            return true;
        else
            return false;
    });
}
 
// Driver code
int main()
{
    int arr[] = { 10, 5, 3, 9, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 7;
    rearrange(arr, n, x);
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}
输出
5 9 10 3 2 

时间复杂度:由于我们使用了一种稳定的 STL,它使用了归并排序的变体,因此时间复杂度为 O(n logn)。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程