Skip to content

Commit

Permalink
leetcode: Add median of two sorted array
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Dec 7, 2023
1 parent 8d3b107 commit 617069b
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 4 deletions.
12 changes: 8 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions leetcode/0004.median-of-two-sorted-arrays/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "lc-0004-median-of-two-sorted-arrays"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
47 changes: 47 additions & 0 deletions leetcode/0004.median-of-two-sorted-arrays/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright (c) 2023 Xu Shaohua <[email protected]>. 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<i32>, nums2: Vec<i32>) -> 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);
}

0 comments on commit 617069b

Please sign in to comment.