美文网首页
215. Kth Largest Element in an A

215. Kth Largest Element in an A

作者: larrymusk | 来源:发表于2017-11-24 21:36 被阅读0次

    利用快速排序分区方法,
    深入理解
    return findXth(nums+index+1, numsSize-index-1,x-index-1);
    else
    return findXth(nums, index, x);

    int partition(int a[], int low, int high)
    {
            int pivot = a[low]; //挖坑
    
    
            while(low < high){
                    for(;(low < high)&&(a[high] >= pivot); high--);
                    a[low] = a[high]; //找到第一个小于pivot的填坑
                    for(;(low < high)&&(a[low] <= pivot); low++);
                    a[high] = a[low];//找到第一个大于pivot的填坑
            }
           //low high相交的时候,把low填入pivot,通知返回low坐标,low代表在排序数组中的下坐标 ,第low+1个
            a[low] = pivot;
    
            return low;
    }
    
    int findXth(int* nums, int numsSize, int x) {
        int index;
        index = partition(nums, 0, numsSize-1);
    
        if(index == x)
            return nums[index];
    
        if(index < x)
            return findXth(nums+index+1, numsSize-index-1,x-index-1);
        else
            return findXth(nums, index, x);
    }
    
    int findKthLargest(int* nums, int numsSize, int k) {
    
            return findXth(nums, numsSize, numsSize-k);
    }

    相关文章

      网友评论

          本文标题:215. Kth Largest Element in an A

          本文链接:https://www.haomeiwen.com/subject/jhxqbxtx.html