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);
        }
    
    
    }
  • 相关阅读:
    c++获取线程id
    一个基于c++的log库
    防止socket程序重启等待2MSL时间
    c++头文件循环引用
    Myeclipse 8.5 优化设置
    来道题 求解释
    MyEclipse常用设置笔记
    Ubuntu 学习笔记
    Linux 下常用命令
    Oracle 学习笔记 常用查询命令篇
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4813506.html
Copyright © 2011-2022 走看看