zoukankan      html  css  js  c++  java
  • 525. Contiguous Array两位求和为1的对数

    [抄题]:

    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.

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    以为要用dp,求个数

    结果求和类的问题还是要用hashmap

    [一句话思路]:

    0,1不好弄中间值,把0改成-1后再求中间

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    0,1不好弄中间值,把0改成-1后再求中间值

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [算法思想:递归/分治/贪心]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    class Solution {
        public int findMaxLength(int[] nums) {
            //cc
            if (nums == null || nums.length == 0) return 0;
        
            //ini: hashmap, 1 to -1, sum
            Map<Integer, Integer> map = new HashMap<>();
            map.put(0, -1);
            int sum = 0, max = 0;
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == 0) nums[i] = -1;
            }   
            
            //for loop, check sum
            for (int i = 0; i < nums.length; i++) {
                sum += nums[i];
                //contain or not
                if (map.containsKey(sum)) {
                    max = Math.max(max, i - map.get(sum));
                }else {
                    map.put(sum, i);
                }
            }
            
            return max;
        }
    }
    View Code
  • 相关阅读:
    在Mac电脑编译c51程序
    Unix程序员的Win10二三事
    macOS webview编程
    Day 6 文件属性与命令执行流程
    Day 5文件管理—三剑客的了解
    Day4 文件管理-常用命令
    Day3 目录结构及文件管理
    Day 2 Bash shell 认识
    Day 1 linux系统的发展史与虚拟机的安装过程
    【Offer】[66] 【构建乘积数组】
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9046314.html
Copyright © 2011-2022 走看看