[leetcode-525-Contiguous Array]

Posted hellowOOOrld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-525-Contiguous Array]相关的知识,希望对你有一定的参考价值。

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

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.

思路:

将0改为-1,将原题目改成求最大连续区间,区间内元素和为0。用map记录当前元素 j 和之前所有元素的和与下标,当map

中存在相同的sum时,说明之前i到j的区间元素和为0。

int findMaxLength(vector<int>& nums)
    {
        for (auto& a:nums) if (a == 0)a = -1;
        map<int, int>mp;
        mp[0] = -1;
        int sum = 0,ret =0;
        for (int i = 0; i < nums.size();i++)
        {
            sum += nums[i];
            if (mp.count(sum))ret = max(ret, i - mp[sum]);
            else mp[sum] = i;
        }
        return ret;         
    }

参考:

http://www.cnblogs.com/liujinhong/p/6472580.html

 

以上是关于[leetcode-525-Contiguous Array]的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 525. Contiguous Array

[LeetCode] 525. Contiguous Array

LeetCode 525. Contiguous Array