zoukankan      html  css  js  c++  java
  • 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.
    

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

    class Solution {
    public:
        //hash表。o(N)的时间复杂度
        //0 1 0 1 0 0 1 1 
        //可以这样考虑 每次遇到0。count就减1,每次遇到1count就加1
        //这样,当往后扫描时,下一次再遇到这个count时,这两个位置之间的0和1就是相等的
        int findMaxLength(vector<int>& nums) {
            map<int,int> m;
            int count = 0, res=0;
            m[count] = 0;
            for(int i=0;i<nums.size();i++){
                if(nums[i] == 0){
                    count--;
                }else{
                    count++;
                }
                if(m.find(count) != m.end()){
                    res = max(res,i+1 - m[count]);
                }else{
                    m[count] = i+1;
                }
            }
            return res;
        }
    };
  • 相关阅读:
    cp
    usr/sbin/inetd
    mysql
    Iptables的规则语法
    CentOS系统安装过程中配置软RAID-0或RAID-1
    25道shell面试题
    虚拟机
    进入单用户模式
    正则表达式
    js操作div的显隐
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/13363057.html
Copyright © 2011-2022 走看看