leetcode_rust/
internal_list_intersections.rs1#![allow(dead_code)]
2
3#[derive(Debug, PartialEq, Eq)]
4pub struct Interval {
5 pub start: i32,
6 pub end: i32,
7}
8
9impl Interval {
10 #[inline]
11 pub fn new(start: i32, end: i32) -> Self {
12 Interval { start, end }
13 }
14}
15
16pub fn interval_intersection(a: Vec<Interval>, b: Vec<Interval>) -> Vec<Interval> {
17 let mut res = vec![];
18 for i in 0..a.len() {
19 for j in 0..b.len() {
20 if a[i].start > b[j].end || a[i].end < b[j].start {
21 continue;
22 }
23
24 let start = a[i].start.max(b[j].start);
25 let end = a[i].end.min(b[j].end);
26
27 res.push(Interval::new(start, end));
28 }
29 }
30 res
31}
32
33#[cfg(test)]
34mod tests {
35 use super::*;
36
37 #[test]
38 fn test1() {
39 let a = vec![
40 Interval::new(0, 2),
41 Interval::new(5, 10),
42 Interval::new(13, 23),
43 Interval::new(24, 25),
44 ];
45 let b = vec![
46 Interval::new(1, 5),
47 Interval::new(8, 12),
48 Interval::new(15, 24),
49 Interval::new(25, 26),
50 ];
51 let c = vec![
52 Interval::new(1, 2),
53 Interval::new(5, 5),
54 Interval::new(8, 10),
55 Interval::new(15, 23),
56 Interval::new(24, 24),
57 Interval::new(25, 25),
58 ];
59 assert_eq!(interval_intersection(a, b), c);
60 }
61}