Java 中未排序数组中的第 K 小元素

2024年9月10日 | 阅读13分钟

在给定的数组中,任务是找到数组的第 k 小的元素,其中 k 总是小于给定数组的大小。

示例

输入

arr[] = {56, 34, 7, 9, 0, 48, 41, 8}

k = 3

输出: 数组的第 3 小的元素是 8。

输入

arr[] = {90, 87, 30, 9, 12, 41, 13, 80, 67, 70}

k = 4

输出: 数组的第 4 小的元素是 30。

方法:对数组进行排序

这是一种直接的方法。你需要对数组进行排序,然后从左边返回第 K 个元素。

文件名: KthSmallestEle.java

输出

For the array: 
56 34 7 9 0 48 41 8 
The 3rd smallest element of the array is: 8


For the array: 
90 87 30 9 12 41 13 80 67 70 
The 4th smallest element of the array is: 30

时间复杂度: 上述程序的时间复杂度取决于 sortArr() 方法中实现的排序技术。在我们的例子中,使用的技术是选择排序。因此,上述程序的时间复杂度为 O(n2),其中 n 是数组中元素的总数。

方法:使用最小堆

也可以使用最小堆来查找数组的第 k 小的元素。

文件名: KthSmallestEle1.java

输出

For the array: 
56 34 7 9 0 48 41 8 
The 3rd smallest element of the array is: 8


For the array: 
90 87 30 9 12 41 13 80 67 70 
The 4th smallest element of the array is: 30

时间复杂度: 上述程序的时间复杂度为 O(n + k * log(n)),其中 n 是数组中元素的总数,k 是需要搜索的最小元素的排名。

方法:使用最大堆

也可以使用最大堆来查找数组的第 k 小的元素。观察以下算法。

步骤 1: 使用输入数组的前 k 个元素(a[0], …, a[k - 1])创建一个最大堆。

步骤 2: 将第 k 个元素之后的每个元素(a[k] 到 a[n - 1])与最大堆的根元素进行比较。在进行比较时,会发生以下两种情况。

情况 1: 如果当前元素小于最大堆的根元素,则用当前元素替换根元素,并调用 heapify() 方法重新排列最大堆中的元素。

情况 2: 如果当前元素大于根元素,则忽略该元素。

文件名: KthSmallestEle2.java

输出

For the array: 
56 34 7 9 0 48 41 8 
The 3rd smallest element of the array is: 8


For the array: 
90 87 30 9 12 41 13 80 67 70 
The 4th smallest element of the array is: 30

时间复杂度: 步骤 1 的时间复杂度为 O(k),步骤 2 的时间复杂度为 O(n - k) * log(k)。因此,上述程序的时间复杂度为 O(k + (n - k) * log(k)),其中 n 是数组中元素的总数,k 是需要搜索的最小元素的排名。

方法:使用快速排序

在快速排序中,我们选择一个枢轴元素,然后将其放置到正确的位置。枢轴元素会将数组划分为两个未排序的子数组。在此方法中,我们不会执行完整的快速排序。实际上,我们将在枢轴元素成为给定数组的第 k 小元素时停止。

文件名: KthSmallestEle3.java

输出

For the array: 
56 34 7 9 0 48 41 8 
The 3rd smallest element of the array is: 8


For the array: 
90 87 30 9 12 41 13 80 67 70 
The 4th smallest element of the array is: 30

时间复杂度: 由于在大多数情况下我们不会完成快速排序,因此上述程序的平均时间复杂度为 O(n)。但是,最坏情况下的时间复杂度为 O(n2),其中 n 是输入数组中元素的总数。

方法:使用有序映射和元素频率

在此方法中,我们将使用一个有序映射,然后将每个元素与其出现频率进行映射。我们已经知道有序映射始终按排序顺序存储数据。因此,我们将不断累加每个元素的出现频率,直到它等于或大于 k,这样就可以从开头找到第 k 个元素,即给定数组的第 k 小的元素。

文件名: KthSmallestEle4.java

输出

For the array: 
56 34 7 9 0 48 41 8 
The 3rd smallest element of the array is: 8


For the array: 
90 87 30 9 12 41 13 80 67 70 
The 4th smallest element of the array is: 30

下一个主题#