标签:
Partial Sort.
class Solution { public: /** * @param nums: A list of integers. * @return: An integer denotes the middle number of the array. */ int partition(vector<int> &nums, int s, int e) { if (s > e) return -1; int pivot = nums[s]; swap(nums[s], nums[e]); int i = s, j = s; while(j < e) { if(nums[j] <= pivot) { swap(nums[i ++], nums[j]); } j ++; } swap(nums[i], nums[e]); return i; } int findKth(vector<int> &nums, int inx, int s, int e) { int pi = partition(nums, s, e); if(pi == inx) return nums[inx]; if (pi < inx) return findKth(nums, inx, pi+1, e); return findKth(nums, inx, s, pi-1); } int median(vector<int> &nums) { size_t len = nums.size(); int mid = len/2 - (len%2?0:1); return findKth(nums, mid, 0, len - 1); } };
标签:
原文地址:http://www.cnblogs.com/tonix/p/4809044.html