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

Kth Largest Element in an Array

时间:2015-09-16 17:23:13      阅读:113      评论: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.

题目:给一个无序数组,求第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);
    }


}

 

Kth Largest Element in an Array

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4813506.html

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