• 525. 连续数组


     方法一:记录0的个数减1的个数有没有出现过

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

    方法二:将0用-1替换,问题转换为求和为0的最长子区间

    class Solution {
        public int findMaxLength(int[] nums) {
            int n = nums.length;
            for(int i = 0; i < n; i++) if(nums[i] == 0) nums[i] = -1;
            Map<Integer,Integer> map = new HashMap<>();
            map.put(0,0);
            int sum = 0, res = 0;
            for(int i = 0; i < n; i++) {
                sum += nums[i];
                if(map.containsKey(sum)) {
                    res = Math.max(res,i - map.get(sum) + 1);
                } else {
                    map.put(sum,i+1);
                }
            }
            return res;
        }
    }
  • 相关阅读:
    Trie树
    递归函数两种方式的区别
    揭开HTTPS的神秘面纱
    补码到底是个什么东西
    浮点数的运算精度丢失
    PHP的stdClass
    2019-10-24
    MySQL存储引擎
    代码整洁之道小结
    NFS4 挂载同主机多个目录
  • 原文地址:https://www.cnblogs.com/yonezu/p/13523863.html
Copyright © 2020-2023  润新知