欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode.525 Contiguous Array

程序员文章站 2022-07-15 14:31:28
...

题目:

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,000.

分析:

class Solution {
    public int findMaxLength(int[] nums) {
        //给定数组,找出子串中0和1个数相等的最长的子串长度
        //思路:该子串一定是由成对的0和1组成的,将其中0全部变为-1(精妙之处)。类似求最长子串的最优解解法
        //再用HashMap存储sum,如果再次出现相同的sum,说明期间0和1保持平衡
        if(nums.length==0||nums==null) return 0;
        
        for(int i=0;i<nums.length;i++){
            if(nums[i]==0){
                nums[i]=-1;
            }
        }
        
        HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
        int sum=0,max=0;
        //初始化第一个和->长度
        hm.put(0,-1);
        for(int i=0;i<nums.length;i++){
            sum+=nums[i];
            if(hm.containsKey(sum)){
                //hm存入长度的和->下标
                max=Math.max(max,i-hm.get(sum));
            }else{
                hm.put(sum,i);
            }
        }
        return max;
    }
}