[LeetCode] 1608. Special Array With X Elements Greater Than or Equal X

You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.

Notice that x does not have to be an element in nums.

Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique.

Example 1:
Input: nums = [3,5]
Output: 2
Explanation: There are 2 values (3 and 5) that are greater than or equal to 2.

Example 2:
Input: nums = [0,0]
Output: -1
Explanation: No numbers fit the criteria for x.
If x = 0, there should be 0 numbers >= x, but there are 2.
If x = 1, there should be 1 number >= x, but there are 0.
If x = 2, there should be 2 numbers >= x, but there are 0.
x cannot be greater since there are only 2 numbers in nums.

Example 3:
Input: nums = [0,4,3,0,4]
Output: 3
Explanation: There are 3 values that are greater than or equal to 3.

Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 1000

特殊数组的特征值。

给你一个非负整数数组 nums 。如果存在一个数 x ,使得 nums 中恰好有 x 个元素 大于或者等于 x ,那么就称 nums 是一个 特殊数组 ,而 x 是该数组的 特征值 。

注意: x 不必 是 nums 的中的元素。

如果数组 nums 是一个 特殊数组 ,请返回它的特征值 x 。否则,返回 -1 。可以证明的是,如果 nums 是特殊数组,那么其特征值 x 是 唯一的 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/special-array-with-x-elements-greater-than-or-equal-x
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路一 - 暴力解

首先是暴力解,因为题目给定了 nums 数组里所有数字的范围,那么也就等同于告诉你了 X 的范围(0 - 1000)。所以我们从 0 到 1000 一个个去试探,看看当 X 等于某个数字 i 的时候,数组是否满足有 i 个数字大于等于 x。

复杂度

时间O(n^2)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int specialArray(int[] nums) {
int candidate = 1;
boolean flag = false;
while (candidate <= 1000) {
int count = 0;
for (int num : nums) {
if (num >= candidate) {
count++;
}
}
if (count == candidate) {
flag = true;
break;
}
candidate++;
}
if (flag == true) {
return candidate;
}
return -1;
}
}

思路二 - counting sort

再来是 counting sort。用一个额外数组记录每个数字出现了多少次,然后从大到小扫描并开始累加已经出现的数字的个数,记为 sum,看看是否存在某个数字 i = sum。从大到小扫描是因为我们需要记录有多少个大于等于 candidate 的数字。

复杂度

时间O(n)
空间O(n)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int specialArray(int[] nums) {
int[] map = new int[1001];
int n = nums.length;
for (int i = 0; i < n; i++) {
int num = nums[i];
map[num]++;
}

int sum = 0;
for (int i = 1000; i >= 0; i--) {
sum += map[i];
if (sum == i) {
return i;
}
}
return -1;
}
}

[LeetCode] 1608. Special Array With X Elements Greater Than or Equal X
https://shurui91.github.io/posts/3793951166.html
Author
Aaron Liu
Posted on
September 12, 2022
Licensed under