zoukankan      html  css  js  c++  java
  • 525. Contiguous Array

    package LeetCode_525
    
    /**
     * 525. Contiguous Array
     * https://leetcode.com/problems/contiguous-array/description/
     *
     * 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.
     * */
    class Solution {
        /*
        * solution: HashMap + Prefix Sum, Time:O(n), Space:O(n)
        * */
        fun findMaxLength(nums: IntArray): Int {
            //key: sum
            //value: the index of where the sum first appeared
            val map = HashMap<Int, Int>()
            map.put(0, -1)
            var result = 0
            var sum = 0
            for (i in nums.indices) {
                sum += if (nums[i] == 0) -1 else nums[i]
                //if contains the sum, we do not update it, because current index in map is the top_index,
                //so can keeping i - top_index is the maximum length
                val lastIndex = map[sum - 0]
                if (lastIndex != null) {
                    result = Math.max(result, i - lastIndex)
                }
                if (!map.containsKey(sum)) {
                    map.put(sum, i)
                }
            }
            //println(map)
            return result
        }
    }
  • 相关阅读:
    图论-最短路
    windows对拍及其应用
    RMQ与st表
    树状数组
    二分和三分题
    [转载]图论500题
    浏览器请求背后的网络数据传输过程
    百度ocr文字识别接口使用
    Mysql启动报错解决方案:Failed to open log (file './mysql-bin.000901', errno 2)
    Mac环境下nginx https配置
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13923267.html
Copyright © 2011-2022 走看看