package com.heu.wsq.leetcode.arr;
/**
* 1608. 特殊数组的特征值
* @author wsq
* @date 2021/1/26
* 给你一个非负整数数组 nums 。如果存在一个数 x ,使得 nums 中恰好有 x 个元素 大于或者等于 x ,那么就称 nums 是一个 特殊数组 ,而 x 是该数组的 特征值 。
* 注意: x 不必 是 nums 的中的元素。
* 如果数组 nums 是一个 特殊数组 ,请返回它的特征值 x 。否则,返回 -1 。可以证明的是,如果 nums 是特殊数组,那么其特征值 x 是 唯一的 。
*
* 示例 1:
* 输入:nums = [3,5]
* 输出:2
* 解释:有 2 个元素(3 和 5)大于或等于 2 。
*
* 链接:https://leetcode-cn.com/problems/special-array-with-x-elements-greater-than-or-equal-x
*/
public class SpecialArray {
public int specialArray(int[] nums){
int n = nums.length;
int[] arr = new int[n + 1];
for (int num : nums) {
int min = Math.min(num, n);
arr[min]++;
}
for (int i = n; i >= 0; i--){
if (i < n){
arr[i] += arr[i+1];
}
if (arr[i] >= i){
return i;
}
}
return -1;
}
public static void main(String[] args) {
int[] nums = {0, 4, 3, 0, 4};
SpecialArray specialArray = new SpecialArray();
int ans = specialArray.specialArray(nums);
System.out.println(ans);
}
}
1608. 特殊数组的特征值
最新推荐文章于 2025-04-07 01:30:00 发布
本文介绍了一种特殊数组——若数组中有x个元素大于或等于x,则称此数组为特殊数组,x即为其特征值。文章详细阐述了如何判断一个数组是否为特殊数组并找出其特征值的方法。
321

被折叠的 条评论
为什么被折叠?



