From 617069b526a482287af8adf6606964645fef66e5 Mon Sep 17 00:00:00 2001 From: Xu Shaohua Date: Thu, 7 Dec 2023 08:35:27 +0800 Subject: [PATCH] leetcode: Add median of two sorted array --- Cargo.lock | 12 +++-- .../Cargo.toml | 7 +++ .../src/main.rs | 47 +++++++++++++++++++ 3 files changed, 62 insertions(+), 4 deletions(-) create mode 100644 leetcode/0004.median-of-two-sorted-arrays/Cargo.toml create mode 100644 leetcode/0004.median-of-two-sorted-arrays/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 50f4bc4d..3d0034ec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -318,6 +318,14 @@ version = "0.1.0" name = "lc-0002-add-two-numbers" version = "0.1.0" +[[package]] +name = "lc-0004-median-of-two-sorted-arrays" +version = "0.1.0" + +[[package]] +name = "lc-0011-container-with-most-water" +version = "0.1.0" + [[package]] name = "lc-0015-3sum" version = "0.1.0" @@ -346,10 +354,6 @@ version = "0.1.0" name = "lc-0191-number-of-1-bits" version = "0.1.0" -[[package]] -name = "lc-11-container-with-most-water" -version = "0.1.0" - [[package]] name = "lc-1114-print-in-order" version = "0.1.0" diff --git a/leetcode/0004.median-of-two-sorted-arrays/Cargo.toml b/leetcode/0004.median-of-two-sorted-arrays/Cargo.toml new file mode 100644 index 00000000..382d6b9f --- /dev/null +++ b/leetcode/0004.median-of-two-sorted-arrays/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "lc-0004-median-of-two-sorted-arrays" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] diff --git a/leetcode/0004.median-of-two-sorted-arrays/src/main.rs b/leetcode/0004.median-of-two-sorted-arrays/src/main.rs new file mode 100644 index 00000000..4c928cbd --- /dev/null +++ b/leetcode/0004.median-of-two-sorted-arrays/src/main.rs @@ -0,0 +1,47 @@ +// Copyright (c) 2023 Xu Shaohua . All rights reserved. +// Use of this source is governed by General Public License that can be +// found in the LICENSE file. + +pub fn find_median_sorted_arrays(nums1: Vec, nums2: Vec) -> f64 { + let len = nums1.len() + nums2.len(); + let mut merged = Vec::with_capacity(len); + let mut i = 0; + let mut j = 0; + + while i < nums1.len() && j < nums2.len() { + if nums1[i] <= nums2[j] { + merged.push(nums1[i]); + i += 1; + } else { + merged.push(nums2[j]); + j += 1; + } + } + while i < nums1.len() { + merged.push(nums1[i]); + i += 1; + } + while j < nums2.len() { + merged.push(nums2[j]); + j += 1; + } + + let half = len / 2; + if len % 2 == 0 { + (merged[half - 1] + merged[half]) as f64 / 2.0 + } else { + merged[half] as f64 + } +} + +fn main() { + let nums1 = vec![1, 3]; + let nums2 = vec![2]; + let median = find_median_sorted_arrays(nums1, nums2); + assert_eq!(median, 2.0); + + let nums1 = vec![1, 2]; + let nums2 = vec![3, 4]; + let median = find_median_sorted_arrays(nums1, nums2); + assert_eq!(median, 2.5); +}