|
| 1 | +/*! |
| 2 | + * 88. Merge Sorted Array |
| 3 | + * |
| 4 | + * * [Problem link](https://leetcode.com/problems/merge-sorted-array/) |
| 5 | + */ |
| 6 | + |
| 7 | +#![allow(dead_code)] |
| 8 | + |
| 9 | +struct Solution {} |
| 10 | + |
| 11 | +// ---------------------------------------------------------------------------- |
| 12 | + |
| 13 | +impl Solution { |
| 14 | + pub fn merge(nums1: &mut Vec<i32>, m: i32, nums2: &mut Vec<i32>, n: i32) { |
| 15 | + let (mut i, mut length) = (0 as usize, m as usize); |
| 16 | + let mut j = 0 as usize; |
| 17 | + while j < n as usize { |
| 18 | + let n2 = nums2[j]; |
| 19 | + if i >= length { |
| 20 | + // if all numbers in nums1 spent |
| 21 | + nums1[i] = n2; |
| 22 | + i += 1; |
| 23 | + length += 1; |
| 24 | + j += 1; |
| 25 | + continue; |
| 26 | + } |
| 27 | + if nums1[i] <= n2 { |
| 28 | + i += 1; |
| 29 | + } else { |
| 30 | + // insert n2 |
| 31 | + let mut k = length; |
| 32 | + while k > i { |
| 33 | + nums1[k] = nums1[k - 1]; |
| 34 | + k -= 1; |
| 35 | + } |
| 36 | + nums1[i] = n2; |
| 37 | + i += 1; |
| 38 | + length += 1; |
| 39 | + j += 1; |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
1 | 45 | #[cfg(test)]
|
2 | 46 | mod tests {
|
| 47 | + use super::*; |
| 48 | + |
| 49 | + #[test] |
| 50 | + fn test_example() { |
| 51 | + let mut nums1 = vec![1, 2, 3, 0, 0, 0]; |
| 52 | + let m = 3; |
| 53 | + let mut nums2 = vec![2, 5, 6]; |
| 54 | + let n = 3; |
| 55 | + Solution::merge(&mut nums1, m, &mut nums2, n); |
| 56 | + let expected = vec![1, 2, 2, 3, 5, 6]; |
| 57 | + assert_eq!(nums1, expected); |
| 58 | + } |
| 59 | + |
| 60 | + #[test] |
| 61 | + fn test_example2() { |
| 62 | + let mut nums1 = vec![0]; |
| 63 | + let m = 0; |
| 64 | + let mut nums2 = vec![1]; |
| 65 | + let n = 1; |
| 66 | + Solution::merge(&mut nums1, m, &mut nums2, n); |
| 67 | + let expected = vec![1]; |
| 68 | + assert_eq!(nums1, expected); |
| 69 | + } |
| 70 | + |
3 | 71 | #[test]
|
4 |
| - fn it_works() { |
5 |
| - assert_eq!(2 + 2, 4); |
| 72 | + fn test_example3() { |
| 73 | + let mut nums1 = vec![2, 0]; |
| 74 | + let m = 1; |
| 75 | + let mut nums2 = vec![1]; |
| 76 | + let n = 1; |
| 77 | + Solution::merge(&mut nums1, m, &mut nums2, n); |
| 78 | + let expected = vec![1, 2]; |
| 79 | + assert_eq!(nums1, expected); |
6 | 80 | }
|
7 | 81 | }
|
0 commit comments