统计 K-Big 索引的数量
难度:
标签:
题目描述
代码结果
运行时间: 112 ms, 内存: 23.0 MB
/*
* 2519. Count the Number of K-Big Indices using Java Streams
*
* Problem Statement:
* Given an array of integers nums and an integer k, we call an index i K-Big if
* there are at least k elements in nums that are greater than nums[i].
* Return the number of K-Big indices.
*
* Example:
* Input: nums = [3, 2, 3, 4, 6], k = 2
* Output: 3
* Explanation: The K-Big indices are 0, 2, and 3 because there are at least 2 elements in the array that are greater than nums[0], nums[2], and nums[3].
*/
import java.util.Arrays;
import java.util.stream.IntStream;
public class CountKBigIndicesStream {
public static long countKBigIndices(int[] nums, int k) {
// Step 1: Sort the array
int[] sorted = nums.clone();
Arrays.sort(sorted);
// Step 2: Use streams to count K-Big indices
return IntStream.of(nums)
.filter(num -> sorted.length - Arrays.binarySearch(sorted, num) - 1 >= k)
.count();
}
public static void main(String[] args) {
int[] nums = {3, 2, 3, 4, 6};
int k = 2;
System.out.println(countKBigIndices(nums, k)); // Output: 3
}
}
解释
方法:
题解的整体思路是使用两次遍历和两个优先队列(最大堆)来计算每个索引 i,左边至少有 k 个元素小于 nums[i] 且右边至少有 k 个元素小于 nums[i] 的索引数量。首先,从左到右遍历数组,对于每个元素,使用最大堆来维护它左边最大的 k 个元素。如果堆的大小达到了 k 并且当前元素大于堆顶元素,标记该索引。然后,从右到左遍历数组,使用另一个最大堆来维护每个元素右边最大的 k 个元素。如果堆的大小达到了 k,当前元素大于堆顶元素,并且该索引在前一次遍历中已被标记,则该索引符合条件,计数增加。最后返回符合条件的索引数量。
时间复杂度:
O(n log k)
空间复杂度:
O(n + k)
代码细节讲解
🦆
如何确保在处理大于堆顶元素的索引时,左侧确实存在至少k个元素小于当前元素?
▷🦆
在算法中使用了两个优先队列(最大堆),这种数据结构的选择是基于什么考虑?
▷🦆
为什么在处理数组的时候需要从左到右和从右到左各进行一次遍历?
▷