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

[leetcode]-525. Contiguous Array

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

题目:

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.

思路:

We iterate through the input array exactly once, keeping track of the number difference between 1 and 0 in the process.If we find that a diff value at index j has been previously seen before in some earlier index i in the array, then we know that the sub-array (i,j] contains the same number of 1 and 0. So we count the length of this subarray and update the max length if necessary.

Time: O(n) --- iterate throught the input array once
Space: O(n) --- the difference number between 1 to 0 is less than n

代码:

    int findMaxLength(int[] nums){
        if(nums == null) return 0;
        //map to store (index, number(1)-number(0))
        Map<Integer, Integer> map = new HashMap<Integer, Integer>(){{put(0,-1);}};
        int diff = 0;
        //max length
        int max = 0;
        for (int i=0;i<nums.length;i++) {
            if(nums[i] == 1){
                diff += 1;
            }else{
                diff -= 1;
            }
            Integer prev = map.get(diff);
            //find previous index, map(curr)==map(prev)
            if (prev != null) {
                if (i - prev > 1 && i - prev > max){
                    max = i - prev;
                };
            }
            else map.put(diff, i);
        }
        return max;
    }

类似的题目:[leetcode]-523-Continuous Subarray Sum

https://blog.csdn.net/ljh0302/article/details/104161207