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:
int median(vector<int> &nums) { 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; } };
|