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;
    }


}

。。

原文地址:https://www.cnblogs.com/guoyu1/p/15634607.html