[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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道数组题,我这里提供两种做法,一种是暴力解,一种是counting sort。
首先是暴力解,因为题目给定了 nums 数组里所有数字的范围,那么也就等同于告诉你了 X 的范围(0 - 1000)。所以我们从 0 到 1000 一个个去试探,看看当 X 等于某个数字 i 的时候,数组是否满足有 i 个数字大于等于 x。
时间O(n * 1000) = O(n)
空间O(1)
Java实现
1 class Solution { 2 public int specialArray(int[] nums) { 3 int candidate = 1; 4 boolean flag = false; 5 while (candidate <= 1000) { 6 int count = 0; 7 for (int num : nums) { 8 if (num >= candidate) { 9 count++; 10 } 11 } 12 if (count == candidate) { 13 flag = true; 14 break; 15 } 16 candidate++; 17 } 18 if (flag == true) { 19 return candidate; 20 } 21 return -1; 22 } 23 }
再来是 counting sort。用一个额外数组记录每个数字出现了多少次,然后从大到小扫描,看看是否存在有若干个数字出现次数的总和 = 某个数字 i。从大到小扫描是因为我们需要记录有多少个比 candidate 大的数字。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int specialArray(int[] nums) { 3 int[] count = new int[1001]; 4 for (int num : nums) { 5 count[num]++; 6 } 7 int total = 0; 8 for (int i = 1000; i >= 0; i--) { 9 total += count[i]; 10 if (i == total) { 11 return i; 12 } 13 } 14 return -1; 15 } 16 }
标签:1608,Elements,return,Greater,candidate,nums,int,there,数组 来源: https://www.cnblogs.com/cnoodle/p/16687755.html