给你一份工做时间表 hours,上面记录着某一位员工天天的工做小时数。
咱们认为当员工一天中的工做小时数大于 8 小时的时候,那么这一天就是「劳累的一天」。
所谓「表现良好的时间段」,意味在这段时间内,「劳累的天数」是严格 大于「不劳累的天数」。
请你返回「表现良好时间段」的最大长度。
输入:hours = [9,9,6,0,6,6,9]
输出:3
解释:最长的表现良好时间段是 [9,9,6]。
方法1——暴力搜索
截取全部的子序列判断是不是[表现良好时间段],使用两个循环遍历
时间复杂度:O(n^2)
空间复杂度:O(1)
1 class Solution(object): 2 def longestWPI(self, hours): 3 """ 4 :type hours: List[int] 5 :rtype: int 6 """ 7 hours=[1 if x >8 else 0 for x in hours] #二值化,大于8->1,小于8->0 8 maxlen=0 9 for i in range(len(hours)) : 10 for j in range(i+1,len(hours)+1) : 11 if sum(hours[i:j]) > (j-i) // 2 : #劳累天数大于总天数的一半 12 maxlen=(j-i) if (j-i) > maxlen else maxlen 13 return maxlen
方法二:
简化这道题目,首先将数组二值化,并写出它们的表现良好的时间段
经过观察发现,其实表现良好的时间段只存在两种形式算法
第一种形式是存在很大特色的,令劳累天=1,不劳累天=-1,其和(sum)=1,因此在序列中,经过判断累加值是否为1,能够判断是否出现[表现良好时间段]数组
在实际算法中,并不判断累加值是否为1,而是判断(累加值-1)是否在记录累加值的字典中,如当此刻累加值为-9,-10在记录的字典中,从-10到-9这一时间段也是表现良好时间段spa
第二种形式经过判断累加值是否为正便可获得code
时间复杂度:O(n)blog
空间复杂度:O(n^2)leetcode
1 class Solution(object): 2 def longestWPI(self, hours): 3 """ 4 :type hours: List[int] 5 :rtype: int 6 :from leetcode-lee215 7 """ 8 res = score = 0 9 seen = {} 10 for i, h in enumerate(hours): 11 score = score + 1 if h > 8 else score - 1 12 if score > 0: 13 res = i + 1 #第一种形式的判断 14 seen.setdefault(score, i) 15 if score - 1 in seen: 16 res = max(res, i - seen[score - 1]) #经过判断score-1是否出现,来获得表现良好时间段 17 return res
#未完待续io