zoukankan      html  css  js  c++  java
  • 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.

    Approach #1: C++.

    class Solution {
    public:
        int findMaxLength(vector<int>& nums) {
            int ans = 0;
            int size = nums.size();
            unordered_map<int, int> prefix_sum;     // store the first position where the sum first appeared.
            int sum = 0;
            for (int i = 0; i < size; ++i) {
                sum += nums[i] ? 1 : -1;
                if (sum == 0) ans = i+1;
                else if (!prefix_sum.count(sum)) prefix_sum[sum] = i;
                else ans = max(ans, i - prefix_sum[sum]);
            }
    
            return ans;
        }
    };
    

      

    Approach #2: Java.

    class Solution {
        public int findMaxLength(int[] nums) {
            for (int i = 0; i < nums.length; ++i) {
                if (nums[i] == 0) nums[i] = -1;
            }
            
            Map<Integer, Integer> sumToIndex = new HashMap<>();
            sumToIndex.put(0, -1);
            int sum = 0, max = 0;
            
            for (int i = 0; i < nums.length; ++i) {
                sum += nums[i];
                if (sumToIndex.containsKey(sum)) {
                    max = Math.max(max, i - sumToIndex.get(sum));
                } else {
                    sumToIndex.put(sum, i);
                }
            }
            return max;
        }
    }
    

      

    Approach #3: Python.

    class Solution(object):
        def findMaxLength(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            count = 0
            max_length = 0
            table = {0 : 0}
            for index, num in enumerate(nums, 1):
                if num == 0:
                    count -= 1
                else:
                    count += 1
                
                if count in table:
                    max_length = max(max_length, index - table[count])
                else:
                    table[count] = index
                    
            return max_length
                
    

      

    Analysis:

    In this problem if we use double cycle traversing the vector to find the subarray, because the length of the given binary array will not exceed 50,000, it will Time Limt Exceeded.

    So we can use a hash table to save time using space.

    First, we have to make the elements in the nums which equal to 0 transform to -1.

    Then we travel the array and calculate the prefix sum. if the sum don't count in hash map, we put sum into the hash table, else i - prefix_sum[sum] is a dummy answer which we want to find.

    Having one thing we have to notice is which if the array is [0, 1], you may finding that the prefix sum never appeared in this case, so it will return 0 finally. but the really answer is 2. How can we solve this problem?

    • In approach one we using a if statemen to judge if the answer equal to 0 we coulde make ans = i + 1 using this way we can solve the problem of initialization.
    • In approach two we push the key and value {0, -1} in the first, this have the same effect with the first one.

      

     
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    subprocess
    bytes(str_, encoding="utf8")
    按文件生成时间 排序 批量与生成同步上传文件
    async
    http trigger 事件源是事件的生产者,函数是事件的处理者
    分片上传
    使用 FFmpeg 处理高质量 GIF 图片
    兴趣 主题 字段 二值化 多值并列属性 拆分 二值化
    打开 回收站
    shell如何查看单个或多个文件的行数或总行数
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9981825.html
Copyright © 2011-2022 走看看