525. Contiguous Array - Medium
前往題目
想法
- 沒什麼想法,看到
subarray
想到會不會是用sliding window
,但貌似不是
思路
- 遇到
0
就-1
,遇到1
就+1
,記錄每個index
的sum
- 疊代的期間,遇到出現過的
sum
就更新最大subarray
長度
簡單來說就是遇到同樣的sum
的時候那兩個相同sum
的index
之間的0
和1
的數量一定是一樣的,可以參考以下影片所畫的圖
另外影片中分成0
和其他總和來討論,但我覺得情況就只有一種,就是上述所說相同sum
中間的01
數量一定是一樣的
Code
class Solution {
public int findMaxLength(int[] nums) {
// Map <Sum, Index>
HashMap<Integer, Integer> seen = new HashMap();
// To handle the answer which starts from the beginning
seen.put(0, -1);
int ans = 0, count = 0;
// Look through the numbers
for (int i = 0; i < nums.length; ++i) {
// -1 if encountered 0, otherwise +1
count += (nums[i] == 0) ? -1 : 1;
// Check if the sum has already appeared before
if (seen.containsKey(count)) {
// Update the maximum subarray length
ans = Math.max(ans, i - seen.get(count));
} else { // First time appears
seen.put(count, i);
}
}
return ans;
}
}
2024/04/30
- 有趣的題目,看了一下之前的想法才想起來怎麼解
525. Contiguous Array - Medium
https://f88083.github.io/2023/12/22/525-Contiguous-Array-Medium/