Kth Largest Element in an Array

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.

题目:给一个无序数组,求第K大元素,不需要滤重。

解题思路:使用快排的思想。后面递归的计算,还可以优化,只需要一半就可以。

public class Solution {

    static int ret = 0;
    static int [] a;

    public static void main(String[] args) {
        
        a=new int[]{11,3,48,5,69,7};
        int res = new Solution().findKthLargest(a,5);
        System.out.println(res);
    }

    public int findKthLargest(int[] nums, int k) {
        if (k >= nums.length) {
            return 0;
        }
        int j=nums.length-1;
        k = nums.length-k;
        qsort(0,j,k);
        return a[k];
    }

    
    private static void qsort(int l, int u,int k) {
        if (u - l < 1)
            return;
        swap(l, randint(l, u));//选取数组中随机一个元素作为划分元素
        int t = a[l];
        int i = l;
        int j = u + 1;
        while (true) {
            do i++; while (i <= u && a[i] < t);//从左侧开始遍历,直到找到一个大于等于t的或者到达最右侧
            do j--; while (a[j] > t);//从右侧开始遍历,找到一个小于等于t的
            if (i > j)//当交叉时 break
                break;
            swap(i, j);//不交叉则将左侧比t大的与右侧比t小的交换
        }
        swap(l, j);//循环终止时,交换a[l]和a[j]
        if (j==k) {
            return ;
        }
        qsort(l, j - 1,k);//对左侧递归调用qsort
        qsort(j + 1, u,k);//对右侧递归调用qsort
    }
    private static void swap(int x, int y) {
        int temp = a[x];
        a[x] = a[y];
        a[y] = temp;
    }

    private static int randint(int a, int b) {
        //产生a与b之间的随机数
        return a + (int) (Math.random() * 100) % (b - a + 1);
    }


}

 

转载于:https://www.cnblogs.com/aboutblank/p/4813506.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值