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

Median

时间:2016-07-04 11:24:05      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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.

分析:

利用quicksort中的partition 方法。

 1 public class Solution {
 2     /**
 3      * @param nums: A list of integers.
 4      * @return: An integer denotes the middle number of the array.
 5      */
 6     public int median(int[] nums) {
 7         // write your code here
 8         if (nums == null || nums.length == 0) return -1;
 9         
10         int k = 0;
11         if (nums.length % 2 == 0) {
12             k = nums.length / 2 - 1;
13         } else {
14             k = nums.length / 2;
15         }
16         return kthElement(k, nums);
17     }
18     
19     public int kthElement(int k, int[] nums) {
20 
21         int start = 0;
22         int end = nums.length - 1;
23         
24         while (start <= end) {
25             int pivot = start;
26             for (int i = start; i <= end - 1; i++) {
27                 if (nums[i] < nums[end]) {
28                     swap(nums, pivot, i);
29                     pivot++;
30                 }
31             }
32             swap(nums, pivot, end);
33             
34             if (pivot == k) {
35                 return nums[pivot];
36             } else if (pivot < k) {
37                 start = pivot + 1;
38             } else {
39                 end = pivot - 1;
40             }
41         }
42         return -1;
43     }
44     
45     private void swap(int[] nums, int index1, int index2) {
46         int temp = nums[index1];
47         nums[index1] = nums[index2];
48         index[index2] = temp; 
49     }
50 }

转载请注明出处: cnblogs.com/beiyeqingteng/

Median

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5639758.html

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