Week 13算法分析作业
来源:互联网 发布:schema.org 知乎 编辑:程序博客网 时间:2024/06/01 21:32
Week 13算法分析作业
LeetCode题目 525. Contiguous Array
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
给定一个二值数值,找出其最长的连续子数组的长度,且子数组的0和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
我的解法
使用Hash函数统计0-1数目
public class Solution { public int findMaxLength(int[] nums) { HashMap<Integer,Integer> map=new HashMap<>(); map.put(0,-1); int zero=0; int one=0; int len=0; for(int i=0;i<nums.length;i++){ if(nums[i]==0){ zero++; }else{ one++; } if(map.containsKey(zero-one)){ len=Math.max(len,i-map.get(zero-one)); }else{ map.put(zero-one,i); } } return len; }}
感想:
很简单的一道题目,还有一种解法是采用动态规划
阅读全文