挑战面试编程:查找数组中第k大的数

版权声明:本文由弓长羊羽发布于http://blog.csdn.net/zhangxiangdavaid/article/details/5048206,本文可以部分或者全部的被引用,但请注明出处

查找数组中第k大的数

问题:
查找出一给定数组中第k大的数。例如[3,2,7,1,8,9,6,5,4],第1大的数是9,第2大的数是8……

思路:
1. 直接从大到小排序,排好序后,第k大的数就是arr[k-1]。
2. 只需找到第k大的数,不必把所有的数排好序。我们借助快速排序中partition过程,一般情况下,在把所有数都排好序前,就可以找到第k大的数。我们依据的逻辑是,经过一次partition后,数组被pivot分成左右两部分:S左、S右。当S左的元素个数|S左|等于k-1时,pivot即是所找的数;当|S左|小于k-1,所找的数位于S右中;当|S左|>k-1,所找的数位于S左中。显然,后两种情况都会使搜索空间缩小。

代码:

<code class="hljs vbscript has-numbering"><span class="hljs-built_in">int</span> Partition(<span class="hljs-built_in">int</span> *arr, <span class="hljs-built_in">int</span> from, <span class="hljs-built_in">int</span> <span class="hljs-keyword">to</span>)
{
    <span class="hljs-built_in">int</span> i, j;
    i = j = from;
    <span class="hljs-keyword">while</span> (j <= <span class="hljs-keyword">to</span>)
    {
        <span class="hljs-keyword">if</span> (arr[j] >= arr[<span class="hljs-keyword">to</span>]) {
            <span class="hljs-built_in">int</span> tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
            i++;
        }
        j++;
    }
    return i - <span class="hljs-number">1</span>;
}
<span class="hljs-built_in">int</span> quickSelect(<span class="hljs-built_in">int</span> *s, <span class="hljs-built_in">int</span> k, <span class="hljs-built_in">int</span> <span class="hljs-built_in">left</span>, <span class="hljs-built_in">int</span> <span class="hljs-built_in">right</span>)
{
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">left</span> == <span class="hljs-built_in">right</span>) return s[<span class="hljs-built_in">left</span>];
    <span class="hljs-built_in">int</span> i;
    i = Partition(s, <span class="hljs-built_in">left</span>, <span class="hljs-built_in">right</span>);
    <span class="hljs-keyword">if</span> (i - <span class="hljs-built_in">left</span> + <span class="hljs-number">1</span> == k) {
        return s[i];
    }
    <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (i - <span class="hljs-built_in">left</span> + <span class="hljs-number">1</span> < k) {
        return quickSelect(s, k - (i - <span class="hljs-built_in">left</span> + <span class="hljs-number">1</span>), i + <span class="hljs-number">1</span>, <span class="hljs-built_in">right</span>);
    }
    <span class="hljs-keyword">else</span> return quickSelect(s, k, <span class="hljs-built_in">left</span>, i - <span class="hljs-number">1</span>);
}
<span class="hljs-built_in">int</span> findKthLargest(<span class="hljs-built_in">int</span>* nums, <span class="hljs-built_in">int</span> numsSize, <span class="hljs-built_in">int</span> k) {
    return quickSelect(nums, k, <span class="hljs-number">0</span>, numsSize - <span class="hljs-number">1</span>);
}</code>

至于”查找数组中第k小的数“,那自然可以举一反三,同样处理了。

点赞