zoukankan      html  css  js  c++  java
  • 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);
        }
    
    
    }
  • 相关阅读:
    操作符重载
    虚继承
    虚函数(2)
    基类与子类的成员函数的关系
    虚函数
    虚函数的简单应用
    齐国的粮食战
    纯虚函数
    类的继承(2)
    输出自定义日期格式
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4813506.html
Copyright © 2011-2022 走看看