Keshawn_lu's Blog

Leetcode 1124. 表现良好的最长时间段

字数统计: 367阅读时长: 1 min
2023/02/14 Share

题目简介:

给你一份工作时间表 hours,上面记录着某一位员工每天的工作小时数。

我们认为当员工一天中的工作小时数大于 8 小时的时候,那么这一天就是「劳累的一天」。

所谓「表现良好的时间段」,意味在这段时间内,「劳累的天数」是严格 大于「不劳累的天数」。

请你返回「表现良好时间段」的最大长度。

示例 1:

1
2
3
输入:hours = [9,9,6,0,6,6,9]
输出:3
解释:最长的表现良好时间段是 [9,9,6]。

示例 2:

1
2
输入:hours = [6,6,6]
输出:0

提示:

  • 1 <= hours.length <= 10^4
  • 0 <= hours[i] <= 16

思路:

我们可以把大于8小时当做1,其余为-1

当遍历到i时,若score > 0,则说明[0, i]符合要求,则res = max(res, i + 1)

否则,我们需要找到第一次出现score - 1时的下标j,则[j + 1, i]score == 1 > 0,因此res = max(res, i - count[score - 1])。 注意到我们此时利用哈希表来存储第一次出现score时的位置。

代码如下:

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
class Solution {
public:
int longestWPI(vector<int>& hours) {

unordered_map<int, int> count;

int res = 0;

int score = 0;
for(int i = 0; i < hours.size(); i++){

if(hours[i] > 8)
score += 1;
else
score -= 1;

if(score > 0)
res = max(res, i + 1);

else if(count.count(score - 1))
res = max(res, i - count[score - 1]);

if(!count.count(score))
count[score] = i;
}

return res;
}
};
CATALOG
  1. 1. 题目简介:
  2. 2. 思路:
  3. 3. 代码如下: