Median
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.
---------------------------- thinking -----------------------------------
quick sort idea
http://codeanytime.blogspot.com/2014/12/median.html
http://www.shuati.info/blog/2014/07/01/Median-in-stream-of-integers/
http://algs4.cs.princeton.edu/23quicksort/
---------------------------- codes ------------------------------------
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 kth = (1 + nums.size()) / 2 - 1;
return medianHelper(nums, 0, nums.size()-1, kth);
}
void swap(vector<int> &nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
int medianHelper(vector<int> &nums, int start, int end, int kth) {
int s = start + 1;
int e = end;
while (s <= e) {
if (nums[s] < nums[start]) {
s++;
} else if (nums[e] > nums[start]) {
e--;
} else {
swap(nums, s, e);
s++;
e--;
}
}
swap(nums, start, e);
if (e == kth) {
return nums[e];
} else if (e < kth) {
//BUG here, the start val should be e+1 instead of e -> the same reason as binary search
return medianHelper(nums, e+1, end, kth);
} else {
return medianHelper(nums, start, e-1, kth);
}
}
};
No comments:
Post a Comment