Median中位数
Description
Given a unsorted array with integers, find the median of it.
A median is the middle number of the array after it is sorted.
If there are even numbers in the array, return the N/2-th number after sorted.
public class Solution {
/**
* @param nums: A list of integers
* @return: An integer denotes the middle number of the array
*/
public int median(int[] nums) {
// write your code here
Arrays.sort(nums) ;
int len = nums.length ;
if(len % 2 == 0){
return nums[len / 2 - 1] ;
}else{
return nums[(len-1) / 2] ;
}
}
}
这篇博客介绍了一个Java实现的算法,用于在未排序的整数数组中找到中位数。通过先对数组进行排序,然后根据数组长度的奇偶性返回中间元素,实现了中位数的查找。该算法适用于数据量较小的情况,对于大型数据集可能需要更高效的方法,如快速选择或堆排序。
1万+

被折叠的 条评论
为什么被折叠?



