面试常见问题-找中位数

来源:互联网 发布:数据分析毕业论文题目 编辑:程序博客网 时间:2024/06/06 09:35

本文将对这个问题进行深入分析。

正常数据量,O(n)的方法

http://www.lintcode.com/en/problem/median
可以用类似快排的方法以O(n)的时间复杂度得到结果。

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        if (nums == null) {            return -1;        }        int k = (nums.length + 1) / 2;        int result = findKth(nums, k);        return result;    }    public int partition(int[] nums, int start, int end) {        int i = start;        int j = end;        int pivotValue = nums[i];        while(i < j) {            while(i < j && nums[j] >= pivotValue) {                j--;            }            nums[i] = nums[j];            while(i < j && nums[i] < pivotValue) {                i++;            }            nums[j] = nums[i];            if (i == j) {                nums[i] = pivotValue;                return i;            }        }        return i;    }    public int helper(int[] nums, int start, int end, int k) {        int loc = partition(nums, start, end);        if (loc == k) {            return nums[loc];        } else if (loc < k) {            return helper(nums, loc + 1, end, k);        } else {            return helper(nums, start, loc - 1, k);        }    }    public int findKth(int[] nums, int k) {        return helper(nums, 0, nums.length - 1, k - 1);    }}

大数据量,单机怎么做

  1. 使用外部归并排序

怎么用堆做?用Java的PriorityQueue实现?

MapReduce

Spark怎么做,有相关函数吗?他们是怎么写的?

对于一个Data Stream,怎么做

0 0
原创粉丝点击