|
| 1 | +/** |
| 2 | + * [1539] Kth Missing Positive Number |
| 3 | + * |
| 4 | + * Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. |
| 5 | + * Return the k^th positive integer that is missing from this array. |
| 6 | + * |
| 7 | + * Example 1: |
| 8 | + * |
| 9 | + * Input: arr = [2,3,4,7,11], k = 5 |
| 10 | + * Output: 9 |
| 11 | + * Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5^th missing positive integer is 9. |
| 12 | + * |
| 13 | + * Example 2: |
| 14 | + * |
| 15 | + * Input: arr = [1,2,3,4], k = 2 |
| 16 | + * Output: 6 |
| 17 | + * Explanation: The missing positive integers are [5,6,7,...]. The 2^nd missing positive integer is 6. |
| 18 | + * |
| 19 | + * |
| 20 | + * Constraints: |
| 21 | + * |
| 22 | + * 1 <= arr.length <= 1000 |
| 23 | + * 1 <= arr[i] <= 1000 |
| 24 | + * 1 <= k <= 1000 |
| 25 | + * arr[i] < arr[j] for 1 <= i < j <= arr.length |
| 26 | + * |
| 27 | + * |
| 28 | + * Follow up: |
| 29 | + * Could you solve this problem in less than O(n) complexity? |
| 30 | + * |
| 31 | + */ |
| 32 | +pub struct Solution {} |
| 33 | + |
| 34 | +// problem: https://leetcode.com/problems/kth-missing-positive-number/ |
| 35 | +// discuss: https://leetcode.com/problems/kth-missing-positive-number/discuss/?currentPage=1&orderBy=most_votes&query= |
| 36 | + |
| 37 | +// submission codes start here |
| 38 | + |
| 39 | +impl Solution { |
| 40 | + pub fn find_kth_positive(arr: Vec<i32>, k: i32) -> i32 { |
| 41 | + arr.iter() |
| 42 | + .enumerate() |
| 43 | + .find(|(i, &val)| val - *i as i32 > k) |
| 44 | + .unwrap_or((arr.len(), &0)) |
| 45 | + .0 as i32 |
| 46 | + + k |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// submission codes end |
| 51 | + |
| 52 | +#[cfg(test)] |
| 53 | +mod tests { |
| 54 | + use super::*; |
| 55 | + |
| 56 | + #[test] |
| 57 | + fn test_1539_example_1() { |
| 58 | + let arr = vec![2, 3, 4, 7, 11]; |
| 59 | + let k = 5; |
| 60 | + |
| 61 | + let result = 9; |
| 62 | + |
| 63 | + assert_eq!(Solution::find_kth_positive(arr, k), result); |
| 64 | + } |
| 65 | + |
| 66 | + #[test] |
| 67 | + fn test_1539_example_2() { |
| 68 | + let arr = vec![1, 2, 3, 4]; |
| 69 | + let k = 2; |
| 70 | + |
| 71 | + let result = 6; |
| 72 | + |
| 73 | + assert_eq!(Solution::find_kth_positive(arr, k), result); |
| 74 | + } |
| 75 | +} |
0 commit comments