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.
這道題給了我們一個二進制的數組,讓找鄰近的子數組使其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 的映射,而不是去更新這個滿足題意的子數組的長度,所以要這么初始化,參見代碼如下:
解法一:
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; } };
下面這種方法跟上面的解法基本上完全一樣,只不過在求累積和的時候沒有用條件判斷,而是用了一個很叼的等式直接包括了兩種情況,參見代碼如下:
解法二:
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 同步地址:
https://github.com/grandyang/leetcode/issues/525
類似題目:
Maximum Size Subarray Sum Equals k
參考資料:
https://leetcode.com/problems/contiguous-array/