|
| 1 | +/** |
| 2 | + * [1608] Special Array With X Elements Greater Than or Equal X |
| 3 | + * |
| 4 | + * 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. |
| 5 | + * Notice that x does not have to be an element in nums. |
| 6 | + * 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. |
| 7 | + * |
| 8 | + * Example 1: |
| 9 | + * |
| 10 | + * Input: nums = [3,5] |
| 11 | + * Output: 2 |
| 12 | + * Explanation: There are 2 values (3 and 5) that are greater than or equal to 2. |
| 13 | + * |
| 14 | + * Example 2: |
| 15 | + * |
| 16 | + * Input: nums = [0,0] |
| 17 | + * Output: -1 |
| 18 | + * Explanation: No numbers fit the criteria for x. |
| 19 | + * If x = 0, there should be 0 numbers >= x, but there are 2. |
| 20 | + * If x = 1, there should be 1 number >= x, but there are 0. |
| 21 | + * If x = 2, there should be 2 numbers >= x, but there are 0. |
| 22 | + * x cannot be greater since there are only 2 numbers in nums. |
| 23 | + * |
| 24 | + * Example 3: |
| 25 | + * |
| 26 | + * Input: nums = [0,4,3,0,4] |
| 27 | + * Output: 3 |
| 28 | + * Explanation: There are 3 values that are greater than or equal to 3. |
| 29 | + * |
| 30 | + * |
| 31 | + * Constraints: |
| 32 | + * |
| 33 | + * 1 <= nums.length <= 100 |
| 34 | + * 0 <= nums[i] <= 1000 |
| 35 | + * |
| 36 | + */ |
| 37 | +pub struct Solution {} |
| 38 | + |
| 39 | +// problem: https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/ |
| 40 | +// discuss: https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/?currentPage=1&orderBy=most_votes&query= |
| 41 | + |
| 42 | +// submission codes start here |
| 43 | + |
| 44 | +impl Solution { |
| 45 | + pub fn special_array(nums: Vec<i32>) -> i32 { |
| 46 | + let mut nums = nums; |
| 47 | + |
| 48 | + nums.sort_unstable(); |
| 49 | + let n = nums.len() as i32; |
| 50 | + |
| 51 | + for i in 0..n + 1 { |
| 52 | + let (mut lo, mut hi) = (0 as i32, (n - 1) as i32); |
| 53 | + let x = i as i32; |
| 54 | + let mut i_idx = -1; |
| 55 | + |
| 56 | + while lo <= hi { |
| 57 | + let mi = lo + (hi - lo) / 2; |
| 58 | + if nums[mi as usize] >= x { |
| 59 | + i_idx = mi; |
| 60 | + hi = mi - 1; |
| 61 | + } else { |
| 62 | + lo = mi + 1; |
| 63 | + } |
| 64 | + } |
| 65 | + if x == n - i_idx { |
| 66 | + return x; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + -1 |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +// submission codes end |
| 75 | + |
| 76 | +#[cfg(test)] |
| 77 | +mod tests { |
| 78 | + use super::*; |
| 79 | + |
| 80 | + #[test] |
| 81 | + fn test_1608_example_1() {} |
| 82 | +} |
0 commit comments