码迷,mamicode.com
首页 > 其他好文 > 详细

Kth Largest Element in an Array

时间:2015-11-22 20:19:46      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

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.

  • 很简单的一个问题,把nums排个序,然后输出第k个大的数
  • 属于分治部分,就顺便使用并归排序实现
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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!