1608. 特殊数组的特征值

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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值