leetcode525. Contiguous Array

題目要求

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

Example 1: 數組

Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.code

Example 2: it

Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.io

Note: The length of the given binary array will not exceed 50,000.class

假設如今有一個由0和1組成的整數數組,問該數組中0和1個數相等的最大的子數組長度。循環

思路一:暴力循環

假設咱們可以算出來從下標0開始全部子數組中0和1的個數,得出numOfZero[i]和numOfOne[i](其實這裏無需用兩個整數數組來記錄,由於0-i這個子數組中1的個數必定等於i+1-numOfZero[i]。map

再對全部子數組按照長度從大到小根據numOfZero開始尋找i-j中0和1相等的狀況,一旦找到,就能夠結束循環。由於這必定是最長的知足0和1數量相等的子數組。im

public int findMaxLength(int[] nums) {  
    int[] numOfOne = new int[nums.length + 1];  
  
    for (int i = 0; i < nums.length; i++) {  
        if (nums[i] == 0) {  
            numOfOne[i + 1] = numOfOne[i];  
        } else {  
            numOfOne[i + 1] = numOfOne[i] + 1;  
        }  
    }  
    int max;  
    boolean finish = false;  
    for (max = nums.length - nums.length % 2; max > 0; max -= 2) {  
        for (int j = 0; j + max < numOfOne.length; j++) {  
            int curNumOfOne = numOfOne[j+max] - numOfOne[j];  
            int curNumOfZero = max - curNumOfOne;  
            if (curNumOfOne == curNumOfZero) {  
                finish = true;  
                break;  
            }  
        }  
        if (finish) {  
            break;  
        }  
    }  
    return max;  
}

思路二:HASHMAP

換個思路來說,若是將0視爲-1,1仍是視爲1,則0,1個數相等的子數組中全部元素的和其實爲0。假設i-j這個子數組中0和1個數相等,其實等價於0-(i-1)以及0-j這兩個子數組中元素的和是相等。所以咱們能夠記錄0-i子數組的元素和,一旦遇到相等的,就說明該🈯️在以前由某個子數組合成過,將兩個下標相減便可獲得知足條件的子數組的長度,co

public int findMaxLength2(int[] nums) {  
    int n = nums.length;  
    int[] map = new int[nums.length * 2 + 1];  
    Arrays.fill(map, -2);  
    int sum = n;  
    map[n] = -1;  
    int max = 0;  
    for (int i = 0 ; i<nums.length ; i++) {  
        sum += (nums[i] * 2 - 1);  
        if (map[sum] == -2) {  
            map[sum] = i;  
        } else {  
            max = Math.max(max, i-map[sum]);  
        }  
    }  
    return max;  
}
相關文章
相關標籤/搜索