LeetCode 1608: Special Array With X Elements Greater Than or Equal X
Problem Description
Explanation
To solve this problem, we can follow these steps:
- Sort the input array
nums
in non-decreasing order. - Iterate over the sorted array and for each element
nums[i]
, check if there are exactlyn - i
elements greater than or equal tonums[i]
. - If such an element
nums[i]
is found, returnn - i
. - If no such element is found after the iteration, return -1.
Time complexity: O(n log n) due to sorting the input array
Space complexity: O(1)
Solutions
import java.util.Arrays;
class Solution {
public int specialArray(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
for (int i = 0; i < n; i++) {
if (nums[i] >= n - i) {
if (i == 0 || nums[i - 1] < n - i) {
return n - i;
}
}
}
return -1;
}
}
Loading editor...