给定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++中,self-balancing-binary-search-tree通过set,map和multimap实现。我们这里有键值对(不仅是键),因此不能在这里使用set。我们也不能直接使用map,因为单个键可以属于多个值,而map允许一个键使用单个值。因此,我们使用多图存储键值对,并且键可以有多个值。
- 将值以X为键将差异存储在多图中。
- 在multimap中,值已经按照关键字(即与X的差异)进行了排序,因为它在内部实现了self-balancing-binary-search-tree。
- 使用映射的值更新数组的所有值,以便该数组具有所需的输出。
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
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)。