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);
        }
    
    
    }
  • 相关阅读:
    tensorflow入门笔记(五) name_scope和variable_scope
    tensorflow入门笔记(四) tf.summary 模块
    tensorflow入门笔记(三) tf.GraphKeys
    tensorflow入门笔记(二) 滑动平均模型
    tensorflow入门笔记(一) tf.app.flags.FLAGS
    iOS友盟推送注意点
    关于gif图片重用消失问题。
    百度地图使用经验
    SQLite语句
    app登录,client和serve的常用字段。
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4813506.html
Copyright © 2011-2022 走看看