给定一个由N 个整数组成的数组arr[] ,表示位于X 轴上的N个点,任务是找到与所有其他点的距离之和最小的点。
例子:
Input: arr[] = {4, 1, 5, 10, 2}
Output: (4, 0)
Explanation:
Distance of 4 from rest of the elements = |4 – 1| + |4 – 5| + |4 – 10| + |4 – 2| = 12
Distance of 1 from rest of the elements = |1 – 4| + |1 – 5| + |1 – 10| + |1 – 2| = 17
Distance of 5 from rest of the elements = |5 – 1| + |5 – 4| + |5 – 2| + |5 – 10| = 13
Distance of 10 from rest of the elements = |10 – 1| + |10 – 2| + |10 – 5| + |10 – 4| = 28
Distance of 2 from rest of the elements = |2 – 1| + |2 – 4| + |2 – 5| + |2 – 10| = 14
Input: arr[] = {3, 5, 7, 10}
Output: 5
天真的方法:
任务是遍历数组,并为每个数组元素计算其与所有其他数组元素的绝对差之和。最后,打印具有最大差异总和的数组元素。
时间复杂度: O(N 2 )
辅助空间: O(1)
高效的方法:为了优化上述方法,其思想是找到数组的中位数。数组的中位数与数组中其他元素的总距离尽可能小。对于具有偶数个元素的数组,有两个可能的中位数,并且两者的总距离相同,返回具有较低索引的那个,因为它更接近原点。
请按照以下步骤解决问题:
- 对给定的数组进行排序。
- 如果N是奇数,则返回第(N + 1 / 2)个元素。
- 否则,返回第(N / 2)个元素。
下面是上述方法的实现:
C++
// C++ Program to implement
// the above approach
#include
using namespace std;
// Function to find median of the array
int findLeastDist(int A[], int N)
{
// Sort the given array
sort(A, A + N);
// If number of elements are even
if (N % 2 == 0) {
// Return the first median
return A[(N - 1) / 2];
}
// Otherwise
else {
return A[N / 2];
}
}
// Driver Code
int main()
{
int A[] = { 4, 1, 5, 10, 2 };
int N = sizeof(A) / sizeof(A[0]);
cout << "(" << findLeastDist(A, N)
<< ", " << 0 << ")";
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
// Function to find median of the array
static int findLeastDist(int A[], int N)
{
// Sort the given array
Arrays.sort(A);
// If number of elements are even
if (N % 2 == 0)
{
// Return the first median
return A[(N - 1) / 2];
}
// Otherwise
else
{
return A[N / 2];
}
}
// Driver Code
public static void main(String[] args)
{
int A[] = { 4, 1, 5, 10, 2 };
int N = A.length;
System.out.print("(" + findLeastDist(A, N) +
", " + 0 + ")");
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program to implement
# the above approach
# Function to find median of the array
def findLeastDist(A, N):
# Sort the given array
A.sort();
# If number of elements are even
if (N % 2 == 0):
# Return the first median
return A[(N - 1) // 2];
# Otherwise
else:
return A[N // 2];
# Driver Code
A = [4, 1, 5, 10, 2];
N = len(A);
print("(" , findLeastDist(A, N),
", " , 0 , ")");
# This code is contributed by PrinciRaj1992
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to find median of the array
static int findLeastDist(int []A, int N)
{
// Sort the given array
Array.Sort(A);
// If number of elements are even
if (N % 2 == 0)
{
// Return the first median
return A[(N - 1) / 2];
}
// Otherwise
else
{
return A[N / 2];
}
}
// Driver Code
public static void Main(string[] args)
{
int []A = { 4, 1, 5, 10, 2 };
int N = A.Length;
Console.Write("(" + findLeastDist(A, N) +
", " + 0 + ")");
}
}
// This code is contributed by rutvik_56
Javascript
(4, 0)
时间复杂度: O(Nlog(N))
辅助空间: O(1)