[LintCode]Find Median of Unsorted Array O(n) quick sort

本文介绍了如何在未排序的整数数组中找到中位数,通过快速排序的方法实现O(n)时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Easy Median
21%
Accepted

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.


Example

Given [4, 5, 1, 2, 3], return 3

Given [7, 9, 4, 5], return 5

Challenge

O(n) time.

记忆中做过这个题目,找不到了。这次做遇到一个bug,做了很久。这个做法作为一个quick sort 的standard。 已末尾元素为pivot

另外,我一律用的是绝对坐标纪录起始与目标 位置,最后要找的位置,也是坐标。比起来找一个size, 绝对坐标是不变的, 更方便, 不需要在右半边情况时候,重新计算size了。

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
        return helper(nums, 0, nums.length-1, (nums.length-1)/2 );
    }
    public int helper(int[] nums, int s, int e, int targetIndex){
        int pivot = nums[e];
        //quick sort       
        int r = e-1, l = s;
        while(l <= r){
            if(nums[l] > pivot){
                swap(nums, l, r);
                r--,l--;
            }
            l++;
        }
        swap(nums, l, e);
        
        if(l == targetIndex){
            return nums[l];
        }else if(l > targetIndex){
            return helper(nums, s, l-1, targetIndex );
        }else{
            return helper(nums, l+1, e, targetIndex );
        }
    }

    public void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值