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

网友投稿 287 2022-08-26

[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: 2Explanation: There are 2 values (3 and 5) that are greater than or equal to 2.

Example 2:

Input: nums = [0,0]Output: -1Explanation: 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: 3Explanation: 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 <= 1000 <= 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​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
下一篇:[leetcode] 937. Reorder Data in Log Files
相关文章

 发表评论

暂时没有评论,来抢沙发吧~