Contiguous Array

2018-07-08 13:24:31

问题描述:

问题求解:

问题规模已经给出是50000量级,显然只能是O(n),至多O(nlogn)的复杂度。本题使用DP和滑动数组都比较棘手,这里给出的方案是preSum + HashMap的策略来进行解决,可以说方法是比较巧妙的。

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

猜你喜欢

转载自www.cnblogs.com/TIMHY/p/9279832.html