标签:
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4]
and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array‘s length.
void merge(int *nums, int start, int mid, int end) { int leftSize = mid - start + 1; int rightSize = end - mid; int i = 0, j = 0; int *left = malloc(sizeof(int)* (leftSize + 1)); int *right = malloc(sizeof(int)* (rightSize + 1) ); for (int i = 0; i < leftSize; i++) left[i] = nums[start + i]; //这里为start+1 left[leftSize] = -9999; //设立尾后的标志,这样就可以直接比较大小,而不需要判断是否为空了 for (int i = 0; i < rightSize; i++) right[i] = nums[mid + i + 1]; //注意这里为mid+i+1;mid属于前半部分 right[rightSize] = -9999; for (int k = start; k <= end; k++) { if (left[i] > right[j]) { nums[k] = left[i]; i++; } else { nums[k] = right[j]; j++; } } free(left); free(right); } void mergeSort(int *nums, int start, int end) { int mid = (start + end) / 2; if (start < end) { mergeSort(nums, start, mid); mergeSort(nums, mid + 1, end); merge(nums, start, mid, end); } } int findKthLargest(int* nums, int numsSize, int k) { mergeSort(nums, 0, numsSize - 1); //传入的大小按照数组的下标传入 return nums[k - 1]; }
Kth Largest Element in an Array
标签:
原文地址:http://www.cnblogs.com/dylqt/p/4986529.html