https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/description
1493. Longest Subarray of 1's After Deleting One Element
給你一個只包含 0 和 1 的陣列,求出一個連續子序列,他需滿足:
1.子序列中最多只能有一個0(可以刪除這個0)。
2.為陣列中的最長子序列。
Example 1:
Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3
numbers with value of 1's.
Example 2:
Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1]
longest subarray with value of 1's is [1,1,1,1,1].
Example 3:
Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.
思路:
1.找連續子序列一樣是先想到滑動窗口,窗口每次都push一個元素,當窗口內的0數量
大於 1 的時候,把左邊的元素 pop 直到 0 的數量等於 1。
2.過程中不斷更新 res 最大值。
Java Code:
--------------------------------------------
class Solution {
public int longestSubarray(int[] nums) {
int zero = 0;
int res = 0;
int left = 0;
for (int right = 0; right < nums.length; right++) {
if (nums[right] == 0) {
zero++;
}
while (zero > 1) {
if (nums[left] == 0) {
zero--;
}
left++;
}
res = Math.max(res, right - left);
}
return res;
}
}
--------------------------------------------
https://i.imgur.com/acHi4CL.png
--
https://i.imgur.com/sjdGOE3.jpg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1688922607.A.699.html