zoukankan      html  css  js  c++  java
  • 15. 数组中的第K个最大元素

    15. 数组中的第K个最大元素

    package 数组;
    
    import jdk.nashorn.internal.ir.CallNode;
    
    import java.util.Random;
    
    public class 数组中的第k大元数 {
        public static void main(String[] args) {
            int[] nums = {1};
            int k = 1;
            数组中的第k大元数 o = new 数组中的第k大元数();
            System.out.println(o.findKthLargest(nums, k));
        }
    
    
        Random random = new Random();
    
        // 快排解法:每次partition都会确定一个数的位置
        // 随机取一个数作为基准,进行partition,看prartion的index的情况
        // 要是相同,就对了
        // 要是大于,就再从前半部分随机选一个数
        // 要是小于,就从后半部分随机选一个数
        public int findKthLargest(int[] nums, int k) {
            int m = nums.length - k;
            return quickSelect(nums, 0, nums.length - 1, m);
        }
    
        public int quickSelect(int[] nums, int start, int end, int k) {
            int index = partition(nums, start, end);
            if (index == k) {
                return nums[index];
            }
            if (index > k) {
                return quickSelect(nums, 0, index - 1, k);
            } else {
                return quickSelect(nums, index + 1, end, k);
            }
        }
    
        // 7,3,2,9,23,8
        public int partition(int[] nums, int start, int end) {
            if(start==end){
                return start;
            }
            int i = random.nextInt(end - start) + start;
            int k = nums[i];
            // 把数组头和k交换,这样才好对数组进行分区
            swap(nums, i, start);
            while (start < end) {
                while (nums[end] > k && start < end) {
                    end--;
                }
                if (start < end) {
                    nums[start] = nums[end];
                    start++;
                }
                while (nums[start] < k && start < end) {
                    start++;
                }
                if (start < end) {
                    nums[end] = nums[start];
                    end--;
                }
            }
            nums[start] = k;
            return start;
        }
    
        public void swap(int[] nums, int i, int j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    
    
    }

    。。

  • 相关阅读:
    小技巧
    常用的交互设计软件
    Android studio 使用SVN需要忽略的文件
    android studio 使用SVN 锁定文件,防止别人修改(基于Android studio 1.4 )
    git 和 github 关系?
    Double 数据保留两位小数一:五舍六入
    设计模式
    Java中关于日期类那些方法
    ios 开源免费接口
    华为招聘机试整理5:简单四则运算
  • 原文地址:https://www.cnblogs.com/guoyu1/p/15634607.html
Copyright © 2011-2022 走看看