5月挑战Day26-Contiguous Array(Medium)

Day26-Contiguous Array(Medium)

问题描述:

Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.

这道题在上个月的挑战里面就有了,求一个数组中最大子数组的长度,这个子数组中0,1的数量相同

Example:

Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
Note: The length of the given binary array will not exceed 50,000.

解法:

在代码里面标注了解释,因为上个月做过了,所以就不细解释了

class Solution:
    def findMaxLength(self, nums: List[int]) -> int:
        if len(nums) <= 1:
            return 0
        #对于求子数组的问题,需要时刻记着求累积和是一种很犀利的工具。这里需要用到一个 trick,遇到1就加1,遇到0,就减1,这样如果某个子数组和为0,就说明0和1的个数相等,这个想法真是太叼了
        #累积和的解法:这道题要求解的是数组中最大的子数组的长度,这个子数组中包含0,1的个数相等。
        #这时可以利用一个字典存储每个位置的累计和,遇到0时减1,遇到1时加1,这时如果当前位置的累积和为0,说明0和1的个数相等,同时如果出现新的数,将其存入hash表中,向后遍历遇到相同的情况时,减去hash表中的数据,就是中间的子数组的长度。同时这个子数组中0,1的个数也相同。
        result = 0
        sums = 0
        temp = {}
        temp[0] = -1
        for i , n in enumerate(nums):
            if n == 0:
                sums -= 1
            else:
                sums += 1
            if sums in temp:
                result = max(result,i - temp[sums])
            else:
                temp[sums] = i
        return result
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值