Leetcode算法學習日誌-525 Contiguous Array

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.

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

題意分析

給一串由0和1構成的數組,求其中0,1個數相同最小數組的長度。

解法分析

當遍歷到0時都看做-1,對所有的元素進行累加,如果加和爲0,則說明前面整個子數組都是0,1相等的子數組,如果和不爲0,則將該和作爲key同相應下標放入map中,若發現加和key存在,則表明從第一次加和爲key時到第二次加和爲key時的元素加和爲0,間隔子數組爲0,1平衡數組,用兩次的下標相減就能得到相應長度,與maxLen比較,取大值。C++代碼如下:

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        map<int,int> myMap;
        int maxLen=0,count=0;
        int i;
        for(i=0;i<nums.size();i++){
            count+=(nums[i]==0)?-1:1;
            if(count==0)
                maxLen=i+1;
            else{
                if(myMap.find(count)==myMap.end())
                    myMap[count]=i;
                else
                    maxLen=max(maxLen,i-myMap[count]);
            }
        }
        return maxLen;
    }
};
改程序的算法複雜度爲O(n)。



發佈了79 篇原創文章 · 獲贊 16 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章