[LeetCode] 525. Contiguous Array 相連的數組

 

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

Example 1:git

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

 

Example 2:github

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.數組

 

這道題給了咱們一個二進制的數組,讓咱們找鄰近的子數組使其0和1的個數相等。對於求子數組的問題,咱們須要時刻記着求累積和是一種很犀利的工具,可是這裏怎麼將子數組的和跟0和1的個數之間產生聯繫呢?咱們須要用到一個 trick,遇到1就加1,遇到0,就減1,這樣若是某個子數組和爲0,就說明0和1的個數相等,這個想法真是太叼了,不過博主木有想出來。知道了這一點,咱們用一個 HashMap 創建子數組之和跟結尾位置的座標之間的映射。若是某個子數組之和在 HashMap 裏存在了,說明當前子數組減去 HashMap 中存的那個子數字,獲得的結果是中間一段子數組之和,必然爲0,說明0和1的個數相等,咱們更新結果 res。注意咱們須要在 HashMap 初始化一個 0 -> -1 的映射,這是爲了當 sum 第一次出現0的時候,即這個子數組是從原數組的起始位置開始,咱們須要計算這個子數組的長度,而不是創建當前子數組之和 sum 和其結束位置之間的映射。好比就拿例子1來講,nums = [0, 1],當遍歷0的時候,sum = -1,此時創建 -1 -> 0 的映射,當遍歷到1的時候,此時 sum = 0 了,若 HashMap 中沒有初始化一個 0 -> -1 的映射,咱們此時會創建 0 -> 1 的映射,而不是去更新這個知足題意的子數組的長度,因此要這麼初始化,參見代碼以下:工具

 

解法一:post

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int res = 0, n = nums.size(), sum = 0;
        unordered_map<int, int> m{{0, -1}};
        for (int i = 0; i < n; ++i) {
            sum += (nums[i] == 1) ? 1 : -1;
            if (m.count(sum)) {
                res = max(res, i - m[sum]);
            } else {
                m[sum] = i;
            }
        }
        return res;
    }
};

 

下面這種方法跟上面的解法基本上徹底同樣,只不過在求累積和的時候沒有用條件判斷,而是用了一個很叼的等式直接包括了兩種狀況,參見代碼以下:url

 

解法二:spa

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int res = 0, n = nums.size(), sum = 0;
        unordered_map<int, int> m{{0, -1}};
        for (int i = 0; i < n; ++i) {
            sum += (nums[i] << 1) -1;
            if (m.count(sum)) {
                res = max(res, i - m[sum]);
            } else {
                m[sum] = i;
            }
        }
        return res;
    }
};

 

Github 同步地址:code

https://github.com/grandyang/leetcode/issues/525htm

 

相似題目:

Maximum Size Subarray Sum Equals k 

 

參考資料:

https://leetcode.com/problems/contiguous-array/

https://leetcode.com/problems/contiguous-array/discuss/99646/Easy-Java-O(n)-Solution-PreSum-%2B-HashMap

https://leetcode.com/problems/contiguous-array/discuss/99652/One-passuse-a-HashMap-to-record-0-1-count-difference

 

LeetCode All in One 題目講解彙總(持續更新中...) 

相關文章
相關標籤/搜索