LeetCode 525. Contiguous Array Maximum Size Subarray Sum Equals k

原题链接在这里:https://leetcode.com/problems/contiguous-array/

题目:

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.

题解:

sum = 0.

When encountering 0, sum--, when encountering 1, sum++.

Record first occurance of sum with index i. 

When same sum appread again, update res.

Time Complexity: O(n). n = nums.length.

Space: O(n).

AC Java: 

 1 class Solution {
 2     public int findMaxLength(int[] nums) {
 3         if(nums == null || nums.length == 0){
 4             return 0;
 5         }
 6         
 7         HashMap<Integer, Integer> hm = new HashMap<>();
 8         hm.put(0, -1);
 9         int sum = 0;
10         int res = 0;
11         
12         for(int i = 0; i<nums.length; i++){
13             sum += nums[i] == 0 ? -1 : 1;
14             if(hm.containsKey(sum)){
15                 res = Math.max(res, i - hm.get(sum));
16             }else{
17                 hm.put(sum, i);
18             }
19         }
20         
21         return res;
22     }
23 }

类似Maximum Size Subarray Sum Equals k.

猜你喜欢

转载自www.cnblogs.com/Dylan-Java-NYC/p/12053933.html