# Code language: Python classSolution: defspecialArray(self, nums: List[int]) -> int: for x inrange(len(nums) + 1): ifsum(a >= x for a in nums) == x: return x return -1
1 2 3 4 5 6 7 8 9 10 11 12 13
// Code language: Java classSolution { publicintspecialArray(int[] nums) { for (intx=1, n = nums.length; x <= n; ++x) { intcnt=0; for (int a: nums) { if (a >= x && ++cnt > x) break; } if (x == cnt) return x; } return -1; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Code language: C++ classSolution { public: intspecialArray(vector<int>& nums){ for (int x = 1, n = nums.size(); x <= n; ++x) { int cnt = 0; for (int a: nums) { if (a >= x && ++cnt > x) break; } if (x == cnt) return x; } return-1; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Code language: JavaScript */ /** * @param {number[]} nums * @return {number} */ var specialArray = function(nums) { for (let x = 1, n = nums.length; x <= n; ++x) { let cnt = 0; for (const a of nums) { if (a >= x && ++cnt > x) break; } if (x == cnt) return x; } return -1; };
# Code language: Python classSolution: defspecialArray(self, nums: List[int]) -> int: n = len(nums) nums.sort() for x inrange(1, n + 1): if n - bisect.bisect_left(nums, x) == x: return x return -1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Code language: Python classSolution: defspecialArray(self, nums: List[int]) -> int: n = len(nums) nums.sort() left, right = -1, n + 1 while left <= right: mid = (left + right) >> 1 if (t := n - bisect.bisect_left(nums, mid)) == mid: return mid elif t < mid: right = mid - 1 else: left = mid + 1 return -1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Code language: Java classSolution { publicintspecialArray(int[] nums) { Arrays.sort(nums); for (intx=1, n = nums.length; x <= n; ++x) { intleft=0, right = n; while (left < right) { intmid= (left + right) >> 1; if (nums[mid] < x) left = mid + 1; else right = mid; } if (x == n - left) return x; } return -1; } }
1 2 3 4 5 6 7 8 9 10 11
// Code language: C++ classSolution { public: intspecialArray(vector<int>& nums){ sort(nums.begin(), nums.end()); for (int x = 1, n = nums.size(); x <= n; ++x) { if (x == n - (lower_bound(nums.begin(), nums.end(), x) - nums.begin())) return x; } return-1; } };