题解 | #连续数组的长度#

连续数组的长度

http://www.nowcoder.com/practice/6e231c66d7864266b55395cde5bcac27

利用哈希表,由于数组中只有0、1,将0全都替换为 -1,则最长的 0,1 子数组就位和为 0 的最长数组长度,利用哈希表值得索引,当和 s 再次出现时,减去响应索引得到最终的值

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param nums int整型一维数组 
# @return int整型
#
from collections import defaultdict
class Solution:
    def findMaxLength(self , nums: List[int]) -> int:
        # write code here
        for i in range(len(nums)):
            if nums[i] == 0:
                nums[i] = -1
        count = defaultdict(int)
        count[0] = -1
        s = max_l = 0
        for i in range(len(nums)):
            s += nums[i]
            if s in count:
                max_l = max(max_l, i - count[s])
            else:
                count[s] = i
        return max_l
            
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务