LeetCode 1107. 每日新用户统计
题目描述
思路分析
解法一:统计首登日期(推荐)
核心思路:
- 先计算每个用户最早出现日期(首登日期)。
- 将首登日期落在目标区间内的用户计数累加。
- 输出按日期升序的统计结果。
复杂度分析:
- 时间复杂度:O(n log n),其中 n 为记录数。
- 空间复杂度:O(n),存储用户首登日期。
import java.util.*;
class Solution {
public Map<String, Integer> newUsersDailyCount(List<Record> records, String startDate, String endDate) {
Map<Integer, String> firstLogin = new HashMap<>();
for (Record r : records) {
String prev = firstLogin.get(r.userId);
if (prev == null || r.date.compareTo(prev) < 0) {
firstLogin.put(r.userId, r.date);
}
}
Map<String, Integer> res = new TreeMap<>();
for (String d : firstLogin.values()) {
if (d.compareTo(startDate) >= 0 && d.compareTo(endDate) <= 0) {
res.put(d, res.getOrDefault(d, 0) + 1);
}
}
return res;
}
static class Record {
int userId;
String date;
Record(int userId, String date) {
this.userId = userId;
this.date = date;
}
}
}
type Record struct {
UserId int
Date string
}
func newUsersDailyCount(records []Record, startDate string, endDate string) map[string]int {
firstLogin := make(map[int]string)
for _, r := range records {
if prev, ok := firstLogin[r.UserId]; !ok || r.Date < prev {
firstLogin[r.UserId] = r.Date
}
}
res := make(map[string]int)
for _, d := range firstLogin {
if d >= startDate && d <= endDate {
res[d]++
}
}
return res
}
相似题目
| 题目 | 难度 | 考察点 |
|---|---|---|
| 1158. 市场分析 I | 中等 | 统计 |
| 1193. 每月交易 I | 中等 | 分组统计 |
| 1327. 列出指定时间段内所有的下单产品 | 简单 | 统计 |
| 1179. 重新格式化部门表 | 简单 | 分组统计 |
| 1107. 每日新用户统计 | 中等 | 统计 |
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0
许可协议,转载请注明出处!