[leetcode]-525. Contiguous Array
程序员文章站
2022-07-15 14:31:52
...
题目:
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.
思路:
We iterate through the input array exactly once, keeping track of the number difference between 1 and 0 in the process.If we find that a diff value at index j has been previously seen before in some earlier index i in the array, then we know that the sub-array (i,j] contains the same number of 1 and 0. So we count the length of this subarray and update the max length if necessary.
Time: O(n) --- iterate throught the input array once
Space: O(n) --- the difference number between 1 to 0 is less than n
代码:
int findMaxLength(int[] nums){
if(nums == null) return 0;
//map to store (index, number(1)-number(0))
Map<Integer, Integer> map = new HashMap<Integer, Integer>(){{put(0,-1);}};
int diff = 0;
//max length
int max = 0;
for (int i=0;i<nums.length;i++) {
if(nums[i] == 1){
diff += 1;
}else{
diff -= 1;
}
Integer prev = map.get(diff);
//find previous index, map(curr)==map(prev)
if (prev != null) {
if (i - prev > 1 && i - prev > max){
max = i - prev;
};
}
else map.put(diff, i);
}
return max;
}
类似的题目:[leetcode]-523-Continuous Subarray Sum
推荐阅读
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST
-
【一天一道LeetCode】#26. Remove Duplicates from Sorted Array
-
LeetCode 33. Search in Rotated Sorted Array && 81. Search in Rotated Sorted Array II
-
Leetcode 33 Search in Rotated Sorted Array
-
LeetCode·33. Search in Rotated Sorted Array
-
leetcode 33. Search in Rotated Sorted Array
-
LeetCode------Search in Rotated Sorted Array
-
LeetCode Search in Rotated Sorted Array
-
Leetcode525-Contiguous Array
-
LeetCode 525. Contiguous Array