文章

1604. 警告一小时内使用相同员工卡大于等于三次的人

问题1604 警告一小时内使用相同员工卡大于等于三次的人 ★☆☆☆☆

https://leetcode.cn/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/

这个题目从思路来说我觉得并不难,属于比较侧重代码书写的题目。按用户归集打卡时间后遍历,遍历过程中先排序,然后判断是否存在一个小时内三次或以上打开记录。因为目标是三次或以上,直接隔一个元素判断就可以。

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
	public List<String> alertNames(String[] keyName, String[] keyTime) {
		Map<String, List<String>> nameTimeMap = new HashMap<>();
		for (int i = 0; i < keyName.length; i++) {
			String name = keyName[i];
			String time = keyTime[i];
			if (nameTimeMap.containsKey(name)) {
				nameTimeMap.get(name).add(time);
			} else {
				List<String> list = new ArrayList<>();
				list.add(time);
				nameTimeMap.put(name, list);
			}
		}

		List<String> alertNameList = new ArrayList<>();

		for (Map.Entry<String, List<String>> entry : nameTimeMap.entrySet()) {
			String name = entry.getKey();
			List<String> timeList = entry.getValue();

			Collections.sort(timeList);

			if (existsThreeOrMoreTimesInOneHourPeriod(timeList)) {
				alertNameList.add(name);
			}
		}

		Collections.sort(alertNameList);

		return alertNameList;
	}

	private boolean existsThreeOrMoreTimesInOneHourPeriod(List<String> timeList) {
		String[] timeArray = timeList.toArray(new String[] {});
		for (int i = 2; i < timeArray.length; i++) {
			String cur = timeArray[i];
			String twoPositionsBefore = timeArray[i - 2];
			if (isOneHourPeriod(twoPositionsBefore, cur)) {
				return true;
			}
		}

		return false;
	}

	private boolean isOneHourPeriod(String time1, String time2) {
		int hour1 = Integer.parseInt(time1.substring(0, 2));
		int minute1 = Integer.parseInt(time1.substring(3, 5));
		int hour2 = Integer.parseInt(time2.substring(0, 2));
		int minute2 = Integer.parseInt(time2.substring(3, 5));

		int hourDiff = Math.abs(hour1 - hour2);
		if (hourDiff == 0) {
			return true;
		} else if (hourDiff == 1) {
			if (minute1 >= minute2) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

在 LeetCode 查看

本文由作者按照 CC BY 4.0 进行授权