前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T50-连续数组

【leetcode刷题】T50-连续数组

作者头像
木又AI帮
修改2019-07-18 10:06:32
3700
修改2019-07-18 10:06:32
举报
文章被收录于专栏:木又AI帮

【英文题目】(学习英语的同时,更能理解题意哟~)

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

Example 1:

代码语言:javascript
复制
Input: [,]
Output: 
Explanation: [, ] is the longest contiguous subarray with equal number of  and .

Example 2:

代码语言:javascript
复制
Input: [,,]
Output: 
Explanation: [, ] (or [, ]) is a longest contiguous subarray with equal number of  and .

Note: The length of the given binary array will not exceed 50,000.

【中文题目】

给定一个二进制数组, 找到含有相同数量的 0 和 1 的最长连续子数组(的长度)。

示例 1:

代码语言:javascript
复制
输入: [,]
输出: 
说明: [, ] 是具有相同数量和的最长连续子数组。

示例 2:

代码语言:javascript
复制
输入: [,,]
输出: 
说明: [, ] (或 [, ]) 是具有相同数量和的最长连续子数组。

注意: 给定的二进制数组的长度不会超过50000。

【思路】

使用一个变量sum0(初始为0),遍历到0则减1,遍历到1则加1。

同时,使用字典d,key为sum0,value为下标。

当sum0在字典中存在时,说明从d[sum0]到该下标为止的0、1元素个数相同。

【代码】

python版本

代码语言:javascript
复制
class Solution(object):
    def findMaxLength(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        res = 
        d = {:-1}
        sum0 = 
        for i, n in enumerate(nums):
            if n == :
                sum0 -= 
            else:
                sum0 += 
            if sum0 in d:
                res = max(res, i - d[sum0])
            else:
                d[sum0] = i
        return res

C++版本

代码语言:javascript
复制
class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int count = ;
        int res = ;
        map<int, int> d;
        d[] = -1;
        for(int i=; i<nums.size(); i++){
            if(nums[i] == )
                count++;
            else
                count--;
            if(d.find(count) == d.end())
                d[count] = i;
            else
                res = max(res, i - d[count]);
        }
        return res;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-04-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档