LeetCode 1126. 查询活跃业务

题目描述

1126. 查询活跃业务

思路分析

解法一:统计超过平均值的事件类型(推荐)

核心思路

  • 先计算每个 event_type 的平均出现次数。
  • 统计每个 business 在多少种事件类型上超过平均值。
  • 超过次数大于 1 的 business 为活跃业务。


复杂度分析

  • 时间复杂度:O(n),其中 n 为记录数。
  • 空间复杂度:O(n),存储分组统计。
import java.util.*;

class Solution {
    public Set<Integer> activeBusinesses(List<Record> records) {
        Map<String, long[]> stat = new HashMap<>();
        for (Record r : records) {
            stat.putIfAbsent(r.eventType, new long[2]);
            long[] s = stat.get(r.eventType);
            s[0] += r.occurrences;
            s[1]++;
        }

        Map<String, Double> avg = new HashMap<>();
        for (Map.Entry<String, long[]> e : stat.entrySet()) {
            long[] s = e.getValue();
            avg.put(e.getKey(), s[0] * 1.0 / s[1]);
        }

        Map<Integer, Integer> cnt = new HashMap<>();
        for (Record r : records) {
            if (r.occurrences > avg.get(r.eventType)) {
                cnt.put(r.businessId, cnt.getOrDefault(r.businessId, 0) + 1);
            }
        }

        Set<Integer> res = new HashSet<>();
        for (Map.Entry<Integer, Integer> e : cnt.entrySet()) {
            if (e.getValue() > 1) {
                res.add(e.getKey());
            }
        }
        return res;
    }

    static class Record {
        int businessId;
        String eventType;
        int occurrences;
        Record(int businessId, String eventType, int occurrences) {
            this.businessId = businessId;
            this.eventType = eventType;
            this.occurrences = occurrences;
        }
    }
}
type Record struct {
    BusinessId int
    EventType  string
    Occurrences int
}

func activeBusinesses(records []Record) map[int]struct{} {
    stat := make(map[string][2]int)
    for _, r := range records {
        s := stat[r.EventType]
        s[0] += r.Occurrences
        s[1]++
        stat[r.EventType] = s
    }

    avg := make(map[string]float64)
    for k, s := range stat {
        avg[k] = float64(s[0]) / float64(s[1])
    }

    cnt := make(map[int]int)
    for _, r := range records {
        if float64(r.Occurrences) > avg[r.EventType] {
            cnt[r.BusinessId]++
        }
    }

    res := make(map[int]struct{})
    for id, c := range cnt {
        if c > 1 {
            res[id] = struct{}{}
        }
    }
    return res
}

相似题目

题目 难度 考察点
1280. 学生们参加各科测试的次数 简单 分组统计
1141. 查询近30天活跃用户数 简单 统计
1193. 每月交易 I 中等 分组统计
1158. 市场分析 I 中等 分组统计
1126. 查询活跃业务 中等 统计
本文作者:
本文链接: https://hgnulb.github.io/blog/2024/63225408
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!