描述
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
Note:
1 <= nums.length <= 100
0 <= nums[i] <= 1000
解析
根据题意,就是要找出一个数字 x ,正好在 nums 中有 x 个数字大于等于 x (还挺绕的)x 可能在也可能不在 nums 中。事先定义一个函数 find(n,l),可以找出在列表 l 中有多少个大于等于 n 的数字的个数。将 nums 从小到大排序,直接遍历从 0 到 len(nums) 的循环,每次判断 find(n, nums) 是否和 n 相等,如果相等直接返回 n ,否则遍历结束表示没有该数字 x ,直接返回 -1 。
解答
class Solution(object):
def specialArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def find(n, l):
return len([i for i in l if i >= n])
nums.sort()
for n in range(0, len(nums) + 1):
if find(n, nums) == n:
return n
return -1
运行结果
Runtime: 36 ms, faster than 32.99% of Python online submissions for Special Array With X Elements Greater Than or Equal X.
Memory Usage: 13.3 MB, less than 77.32% of Python online submissions for Special Array With X Elements Greater Than or Equal X.
原题链接:leetcode.com/problems/sp…
您的支持是我最大的动力