面试常见问题-找中位数

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

正常数据量,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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值