-
Notifications
You must be signed in to change notification settings - Fork 1
/
4.median-of-two-sorted-arrays.rs
69 lines (58 loc) · 1.64 KB
/
4.median-of-two-sorted-arrays.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
* @lc app=leetcode id=4 lang=rust
*
* [4] Median of Two Sorted Arrays
*/
// @lc code=start
impl Solution {
pub fn find_median_sorted_arrays(nums1: Vec<i32>, nums2: Vec<i32>) -> f64 {
let l1 = nums1.len();
let l2 = nums2.len();
let mid = (l1 + l2 - 1) / 2;
let odd = (l1 + l2) % 2 == 1;
let mut i = 0;
let mut j = 0;
while i + j < mid {
if (i < l1) {
if (j < l2) {
if (nums1[i] < nums2[j]) {
i += 1;
} else {
j += 1;
}
} else {
i += 1;
}
} else {
j += 1;
}
}
let mut median: f64;
if (odd) {
let (nextmin, i, j) = Self::next_min(&nums1, &nums2, i, j);
nextmin as f64
} else {
let (nextmin1, i, j) = Self::next_min(&nums1, &nums2, i, j);
let (nextmin2, i, j) = Self::next_min(&nums1, &nums2, i, j);
(nextmin1 + nextmin2) as f64 / 2 as f64
}
}
pub fn next_min(nums1: &Vec<i32>, nums2: &Vec<i32>, i: usize, j: usize) -> (i32, usize, usize) {
let l1 = nums1.len();
let l2 = nums2.len();
if (i < l1) {
if (j < l2) {
if (nums1[i] < nums2[j]) {
(nums1[i], i+1, j)
} else {
(nums2[j], i, j+1)
}
} else {
(nums1[i], i+1, j)
}
} else {
(nums2[j], i, j+1)
}
}
}
// @lc code=end