给定一个大小为N的数组arr[] ,任务是找到一个数组元素与另一个数组的所有元素的绝对差的最小总和。
Input: arr[ ] = {1, 2, 3, 4, 5}, N = 5
Output: 3
Explanation:
For arr[0](= 1): Sum = abs(2 – 1) + abs(3 – 1) + abs(4 – 1) + abs(5 – 1) = 10.
For arr[1](= 2): Sum = abs(2 – 1) + abs(3 – 2) + abs(4 – 2) + abs(5 – 2) = 7.
For arr[2](= 3): Sum = abs(3 – 1) + abs(3 – 2) + abs(4 – 3) + abs(5 – 3) = 6 (Minimum).
For arr[3](= 4): Sum = abs(4 – 1) + abs(4 – 2) + abs(4 – 3) + abs(5 – 4) = 7.
For arr[0](= 1): Sum = 10.
Input: arr[ ] = {1, 2, 3, 4}, N = 4
Output: 2
处理方法:通过观察所有数组元素的绝对差之和对于数组的中位数最小,可以解决该问题。请按照以下步骤解决问题:
- 对数组arr[] 进行排序。
- 打印排序数组的中间元素作为所需答案。
下面是上述方法的实现:
C++
// C++ implementation
// of the above approach
#include
using namespace std;
// Function to return the array element
// having minimum sum of absolute
// differences with other array elements
void minAbsDiff(int arr[], int n)
{
// Sort the array
sort(arr, arr + n);
// Print the middle element
cout << arr[n / 2] << endl;
}
// Driver Code
int main()
{
int n = 5;
int arr[] = { 1, 2, 3, 4, 5 };
minAbsDiff(arr, n);
return 0;
}
Java
// Java program for the above approach
import java.util.Arrays;
public class GFG
{
// Function to return the array element
// having minimum sum of absolute
// differences with other array elements
static void minAbsDiff(int arr[], int n)
{
// Sort the array
Arrays.sort(arr);
// Print the middle element
System.out.println(arr[n / 2]);
}
// Driver code
public static void main(String[] args)
{
int n = 5;
int arr[] = { 1, 2, 3, 4, 5 };
minAbsDiff(arr, n);
}
}
// This code is contributed by abhinavjain194
输出:
3
时间复杂度: O(NlogN)
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live