码迷,mamicode.com
首页 > 其他好文 > 详细

Median

时间:2017-05-28 09:59:01      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:median   middle   public   quick   sort   start   tar   UI   use   

O(n) worst, O(nlogn) average. Use quickSort

This is quickSort

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 || nums.length == 0) {
            return 0;
        }
        quickSort(nums, 0, nums.length - 1);
        return nums[(nums.length - 1) / 2];
    }
    
    private void quickSort(int[] nums, int start, int end) {
        if (start >= end) {
            return;
        }
        
        int left = start;
        int right = end;
        int pivot = nums[start + (end - start) / 2];
        while (left <= right) {
            while (left <= right && nums[left] < pivot) {
                left++;
            }
            while (left <= right && nums[right] > pivot) {
                right--;
            }
            if (left <= right) {
                int tmp = nums[left];
                nums[left] = nums[right];
                nums[right] = tmp;
                left++;
                right--;
            }
        }
        
        quickSort(nums, start, right);
        quickSort(nums, left, end);
    }
}

 

Median

标签:median   middle   public   quick   sort   start   tar   UI   use   

原文地址:http://www.cnblogs.com/codingEskimo/p/6914948.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!