leetcode 525. Contiguous Array

257 篇文章 17 订阅

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.

这道题我想用DP做的,结果Memory Limit Exceeded了,真是屮艸芔茻...

注意一个测试用例:[0,0,0,1,1,1,0],返回结果 6 。

这道题有点类似于之前的一道题 http://blog.csdn.net/huanghanqian/article/details/77054149,从树的根一直遍历到叶,找到所有的 和为target的路径(不一定非得以根结点开始以叶节点结尾)。只要把这道题的0想象成-1,就会转化为:找到最长的串使得 和为0。然后解决方法就跟之前的那道题类似啦。

The idea is to change 0 in the original array to -1. Thus, if we find SUM[i, j] == 0 then we know there are even number of -1 and 1 between index i and j. Also put the sum to index mapping to a HashMap to make search faster.

public int findMaxLength(int[] nums) {
	int n=nums.length;
	if(n<2){
		return 0;
	}
	int maxLength=0;
	//map存储 <[0,index]范围内的和,index> ,且 是 得到该和的最小的index
	HashMap<Integer, Integer> map=new HashMap<Integer, Integer>();
	int sum=0;//sum是0~i范围的和
	map.put(0, -1);
	for(int i=0;i<n;i++){
		if(nums[i]==1){
			sum+=1;
		}
		else{
			sum+=-1;
		}
		//sum-sum=0
		if(map.get(sum)!=null){
			int length=i-map.get(sum);
			if(length>maxLength){
				maxLength=length;
			}
		}
		else {
			map.put(sum,i);
		}
	}
	return maxLength;
}

大神们也都用的这个解法。

这道题有solutions: https://leetcode.com/problems/contiguous-array/solution/#approach-3-using-hashmap-accepted
Approach #3 Using HashMap [Accepted]

Algorithm

我们使用一个 HashMap mapmap 来存储 (index, count)(index,count),当我们遇到一个之前未曾出现的count时,将该条目push进map。之后再碰到该count时,使用它对应的 index 来找 最大的使得count为0的子串。

Java

public class Solution {

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

Complexity Analysis

  • Time complexity : O(n)O(n). The entire array is traversed only once.

  • Space complexity : O(n)O(n). Maximum size of the HashMap mapmap will be \text{n}n, if all the elements are either 1 or 0.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值