2446.判断两个事件是否存在冲突
链接:2446.判断两个事件是否存在冲突
难度:Easy
标签:数组、字符串
简介:如果两个事件之间存在冲突,返回 true ;否则,返回 false 。
题解 1 - typescript
- 编辑时间:2022-10-23
- 执行用时:56ms
- 内存消耗:42.4MB
- 编程语言:typescript
- 解法介绍:化成分钟表示后比较。
function toTime(data: string) {
  const time = data.split(':').map(v => +v);
  return time[0] * 60 + time[1];
}
function haveConflict(event1: string[], event2: string[]): boolean {
  let [l1, r1] = [toTime(event1[0]), toTime(event1[1])];
  let [l2, r2] = [toTime(event2[0]), toTime(event2[1])];
  if (l1 > l2) {
    [l1, r1, l2, r2] = [l2, r2, l1, r1];
  }
  return r1 >= l2;
}
题解 2 - python
- 编辑时间:2023-05-17
- 执行用时:36ms
- 内存消耗:16.1MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
    def haveConflict(self, event1: List[str], event2: List[str]) -> bool:
        def to_time(t: str):
            return int(t[:2]) * 60 + int(t[3:])
        s1, e1 = to_time(event1[0]), to_time(event1[1])
        s2, e2 = to_time(event2[0]), to_time(event2[1])
        if s1 > s2:
            s1, e1, s2, e2 = s2, e2, s1, e1
        return e1 >= s2
题解 3 - cpp
- 编辑时间:2023-05-17
- 内存消耗:11.1MB
- 编程语言:cpp
- 解法介绍:转换成数字后比大小。
class Solution {
public:
    bool haveConflict(vector<string>& event1, vector<string>& event2) {
        auto to_time = [&](string t) -> int {
            return ((t[0] - '0') * 10 + t[1] - '0') * 60 + (t[3] - '0') * 10 + t[4] - '0';
        };
        int s1 = to_time(event1[0]), e1 = to_time(event1[1]),
            s2 = to_time(event2[0]), e2 = to_time(event2[1]);
        if (s1 > s2) swap(s1, s2), swap(e1, e2);
        return e1 >= s2;
    }
};
题解 4 - rust
- 编辑时间:2023-05-17
- 内存消耗:2MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
    pub fn have_conflict(event1: Vec<String>, event2: Vec<String>) -> bool {
        let to_time =
            |s: &String| -> i32 { s[0..2].parse::<i32>().unwrap() * 60 + s[3..].parse::<i32>().unwrap() };
        let (mut s1, mut e1, mut s2, mut e2) = (
            to_time(&event1[0]),
            to_time(&event1[1]),
            to_time(&event2[0]),
            to_time(&event2[1]),
        );
        if s1 > s2 {
            unsafe {
                std::ptr::swap(&mut s1, &mut s2);
                std::ptr::swap(&mut e1, &mut e2);
            }
        }
        e1 >= s2
    }
}