[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.

思路:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章