c# leetcode 525. 連續數組(哈希)

給定一個二進制數組, 找到含有相同數量的 0 和 1 的最長連續子數組(的長度)。

示例 1:

輸入: [0,1]
輸出: 2
說明: [0, 1] 是具有相同數量0和1的最長連續子數組。

示例 2:

輸入: [0,1,0]
輸出: 2
說明: [0, 1] (或 [1, 0]) 是具有相同數量0和1的最長連續子數組。

注意: 給定的二進制數組的長度不會超過50000。

~~

public int FindMaxLength(int[] nums)
        {
            var count = 0;
            var dict = new Dictionary<int, int>();
            dict[0] = -1;
            var maxL = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                count += (nums[i] == 0 ? -1 : 1);
                if (dict.ContainsKey(count))
                {
                    maxL = Math.Max(maxL, i - dict[count]);
                }
                else
                {
                    dict[count]= i;
                }
            }
            return maxL;
        }

一:用暴力破解

public class Solution {
    public int FindMaxLength(int[] nums) {
int maxLin = 0;
            for (int start = 0; start < nums.Length; start++)
            {
                int zeroes = 0, one = 0;
                for (int end = start; end < nums.Length; end++)
                {
                    if (nums[end]==0)
                    {
                        zeroes++;
                    }
                    else
                    {
                        one++;
                    }
                    if (zeroes==one)
                    {
                        maxLin = Math.Max(maxLin, end - start + 1);
                    }
                }
            }
            return maxLin;
    }
}

暴力破解的思維還是要有的,這是最後準確率的底線, 儘管經常會超時。

經典哈希算法:

public static int FindMaxLength(int[] nums)
        {
            Dictionary<int, int> dict = new Dictionary<int, int>();
            int count = 0;
            int maxLength = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                if (nums[i] == 1) count++;
                if (nums[i] == 0) count--;

                if (dict.ContainsKey(count))
                    maxLength = Math.Max(maxLength, i - dict[count]);
                else
                    dict[count] = i;

                if (count == 0)    //If count ever becomes 0 that means from start till current index i, we have max contiguous array. 
                    maxLength = i + 1;
            }
            return maxLength; 
        }

 

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