📌  相关文章
📜  找到与所有其他数组元素的绝对差之和最小的数组元素

📅  最后修改于: 2021-10-25 06:47:55             🧑  作者: Mango

给定一个大小为N的数组arr[] ,任务是找到一个数组元素与另一个数组的所有元素的绝对差的最小总和。

处理方法:通过观察所有数组元素的绝对差之和对于数组的中位数最小,可以解决该问题。请按照以下步骤解决问题:

  • 对数组arr[] 进行排序。
  • 打印排序数组的中间元素作为所需答案。

下面是上述方法的实现:

C++
// C++ program for 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


Python3
# Python3 program for the above approach
 
# Function to return the array element
# having minimum sum of absolute
# differences with other array elements
def minAbsDiff(arr, n):
 
    # Sort the array
    arr.sort()
 
    # Print the middle element
    print(arr[n // 2])
 
# Driver Code
if __name__ == '__main__':
 
    n = 5
    arr = [ 1, 2, 3, 4, 5 ]
     
    minAbsDiff(arr, n)
 
# This code is contributed by SURENDRA_GANGWAR


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
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
    Array.Sort(arr);
     
    // Print the middle element
    Console.WriteLine(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 ankThon


Javascript


输出:
3

时间复杂度: O(NlogN)
辅助空间: O(1)

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