Java学习手册:(数据结构与算法-数组)如何找出数组中第k个最小的数?

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/MaybeForever/article/details/100021010

问题描述:给定一个无序的数组,从一个数组中找出第k个最小的数。例如,对于给定数组{1,5,2,6,8,0,6},其中第4小的数为5。

方法一:对数组进行排序,然后返回其第k个元素。
方法一代码如下:

package com.haobi;

import java.util.Arrays;
/*
 * 如何找出数组中第k个最小的数?
 */
public class Test12 {
	public static void main(String[] args) {
		int[] arr = {1,5,2,6,8,0,6};
		int k = 4;
		System.out.println(getKMin(arr, k));
	}
	
	public static int getKMin(int[] a, int k) {
		Arrays.sort(a);
		return a[k-1];
	}
}

方法二:“剪枝”法,按照快排的思想来实现。选择一个基准元素,进行一次快排,找到其在数组中的最终位置,与k进行比较。如果相等,则返回当前位置;如果小于k,则k在该基准元素的右侧,缩小快排区域,继续搜索;如果大于k,同理。
方法二代码如下:

package com.haobi;

import java.util.Arrays;
/*
 * 如何找出数组中第k个最小的数?
 */
public class Test13 {
	public static void main(String[] args) {
		int[] arr = {1,5,2,6,8,0,6};
		int k = 4;
		System.out.println(getKMin(arr, k));
	}
	
	public static int getKMin(int[] a, int k) {
		if(a == null || a.length < k) {
			return Integer.MIN_VALUE;
		}
		return quickSort(a,0,a.length-1,k);
	}
	
	public static int quickSort(int[] array, int low, int high, int k) {
		if(low > high) {
			return Integer.MIN_VALUE;
		}
		int i = low + 1;
		int j = high;
		int temp = array[i];//基准元素
		//快排
		while(i < j) {
			while(i<j && array[j]>=temp) {
				j--;
			}
			if(i<j) {
				array[i++] = array[j];
			}
			while(i<j && array[i]<temp) {
				i++;
			}
			if(i<j) {
				array[j--] = array[i];
			}
		}
		//基准元素到最终位置
		array[i] = temp;
		if(i+1 == k) {//当前元素恰好是第k个
			return temp;
		}else if(i+1 > k) {//k在左侧
			return quickSort(array,low,i-1,k);
		}else {
			return quickSort(array,i+1,high,k);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/MaybeForever/article/details/100021010
今日推荐