Median

Description:

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.

分析:

思路:

参考:

  1. What is the most efficient algorithm to find the kth smallest element in an array having n unordered elements?
  2. Quickselect
  3. Median - C++

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

class Solution {
public:
/**
* @param nums: A list of integers.
* @return: An integer denotes the middle number of the array.
*/
int median(vector<int> &nums) {
// write your code here
int left = 0;
int right = nums.size();

int k = -1;
if (right % 2 ==1) k = right / 2;
else k = right / 2 - 1;

return select_kth(nums, left, right - 1, k);
}

int select_kth(vector<int> &nums, int left, int right, int k) {
if (left == right) return nums[left];
int pivot = left + floor(rand() % (right - left + 1));

pivot = partition(nums, left, right, pivot);
if (pivot == k) return nums[k];
else if (pivot < k) return select_kth(nums, pivot+1, right, k);
else return select_kth(nums, left, pivot-1, k);
}

int partition(vector<int> &nums, int left, int right, int pivot) {
int val = nums[pivot];
swap(nums, pivot, right);
int currIndex = left;

for (int i = left;i < right;i++) {
if (nums[i] < val) {
swap(nums, currIndex, i);
currIndex++;
}
}
swap(nums, currIndex, right);

return currIndex;
}

void swap(vector<int> &nums, int left, int right) {
int tem = nums[left];
nums[left] = nums[right];
nums[right] = tem;
}
};