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

Description

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.

Example 4:

Input: nums = [3,6,7,7,0]
Output: -1

Constraints:

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

分析

题目的意思是:给你一个数组,找出其中X个元素大于或者等于X的值,题目给出的这个是唯一的,其中一种暴力破解的方法就是一个一个的判断是否满足要求,只要找出来一个就行了。还有一种更好的方法,首先对数组进行排序,然后从左到右进行判断,如果n-i<=nums[i]说明找到了一个符合条件的值,但是题目中给出x是唯一的,因此不会是重复值,用prev记录一下前面遍历的值,利用n-i>prev可以保证这一点。比如

[1,1,2]

这个反例,应该返回-1,不应该返回1哈。这个想法很难想到,我也没想到哈哈哈哈

代码

class Solution:
    def specialArray(self, nums: List[int]) -> int:
        n=len(nums)
        
        prev=-1
        nums.sort()
        for i in range(n):
            if(n-i<=nums[i] and n-i>prev):
                return n-i
            prev=nums[i]
        return -1

参考文献

[LeetCode] Simple Python / c solution

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值