3759. Count Elements With at Least K Greater Values
Description
You are given an integer array nums of length n and an integer k.
An element in nums is said to be qualified if there exist at least k elements in the array that are strictly greater than it.
Return an integer denoting the total number of qualified elements in nums.
Example 1:
Input: nums = [3,1,2], k = 1
Output: 2
Explanation:
The elements 1 and 2 each have at least k = 1 element greater than themselves.
βββββββNo element is greater than 3. Therefore, the answer is 2.
Example 2:
Input: nums = [5,5,5], k = 2
Output: 0
Explanation:
Since all elements are equal to 5, no element is greater than the other. Therefore, the answer is 0.
Constraints:
1 <= n == nums.length <= 1051 <= nums[i] <= 1090 <= k < n
Solutions
Solution 1: Sorting
If \(k = 0\), then all elements in the array are qualified elements, and we can directly return the length of the array.
Otherwise, we sort the array, and let \(n\) be the length of the sorted array. For each index \(i\) satisfying \(0 \leq i < n - k\), if the element at index \(i\) is strictly less than the element at index \(n - k\), then it is a qualified element. We just need to count the number of such elements and return it.
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(\log n)\), where \(n\) is the length of the array \(\textit{nums}\).
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |