|
| 1 | +// 3133. Minimum Array End |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/minimum-array-end/ |
| 5 | +// |
| 6 | +// Tags: Bit Manipulation |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// For n steps choose the smallest next number that me can use. Barely passes. |
| 11 | + /// |
| 12 | + /// Time complexity: O(n) |
| 13 | + /// Space complexity: O(1) |
| 14 | + /// |
| 15 | + /// Runtime 1735 ms Beats 100% |
| 16 | + /// Memory 2.16 MB Beats 100% |
| 17 | + #[allow(dead_code)] |
| 18 | + pub fn min_end_on(n: i32, x: i32) -> i64 { |
| 19 | + let x = x as i64; |
| 20 | + (0..n - 1).fold(x, |acc, _| (acc + 1) | x) |
| 21 | + } |
| 22 | + |
| 23 | + /// For n steps choose the smallest next number that me can use. Barely passes. |
| 24 | + /// |
| 25 | + /// Time complexity: O(n) |
| 26 | + /// Space complexity: O(1) |
| 27 | + /// |
| 28 | + /// Runtime 1735 ms Beats 100% |
| 29 | + /// Memory 2.16 MB Beats 100% |
| 30 | + pub fn min_end(n: i32, x: i32) -> i64 { |
| 31 | + let mut x = x as i64; |
| 32 | + let mut n = n as i64 - 1; |
| 33 | + let mut b = 1i64; |
| 34 | + for _ in 0..64i64 { |
| 35 | + if b & x == 0 { |
| 36 | + x |= (n & 1) * b; |
| 37 | + n >>= 1; |
| 38 | + } |
| 39 | + b <<= 1; |
| 40 | + } |
| 41 | + x |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// Tests. |
| 46 | +fn main() { |
| 47 | + let tests = [(3, 4, 6), (2, 7, 15)]; |
| 48 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 49 | + let mut success = 0; |
| 50 | + for (i, t) in tests.iter().enumerate() { |
| 51 | + let res = Solution::min_end(t.0, t.1); |
| 52 | + if res == t.2 { |
| 53 | + success += 1; |
| 54 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 55 | + } else { |
| 56 | + println!( |
| 57 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 58 | + i, t.2, res |
| 59 | + ); |
| 60 | + } |
| 61 | + } |
| 62 | + println!(); |
| 63 | + if success == tests.len() { |
| 64 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 65 | + } else if success == 0 { |
| 66 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 67 | + } else { |
| 68 | + println!( |
| 69 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 70 | + tests.len() - success |
| 71 | + ) |
| 72 | + } |
| 73 | +} |
0 commit comments