Skip to content

Commit 0c767f0

Browse files
refactor 1493
1 parent 166b9f6 commit 0c767f0

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/main/java/com/fishercoder/solutions/_1493.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,37 @@ public int longestSubarray(int[] nums) {
3939
return longest;
4040
}
4141
}
42+
43+
public static class Solution2 {
44+
/**
45+
* Sliding window solution
46+
* Credit: https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/708112/JavaC%2B%2BPython-Sliding-Window-at-most-one-0
47+
* <p>
48+
* we initialize k to be one, meaning we could have at most one zero in the sliding window
49+
* i is the left pointer
50+
* j is the right pointer
51+
* when j encounters a zero, we'll decrement k by one;
52+
* and once k becomes negative, that means we have more than one zeroes in the sliding window,
53+
* so we'll have to move left pointer to the right until k becomes not negative;
54+
* along this process, we use result to hold the max length of this sliding window
55+
*/
56+
public int longestSubarray(int[] nums) {
57+
int i = 0;
58+
int k = 1;
59+
int result = 0;
60+
for (int j = 0; j < nums.length; j++) {
61+
if (nums[j] == 0) {
62+
k--;
63+
}
64+
while (k < 0) {
65+
if (nums[i] == 0) {
66+
k++;
67+
}
68+
i++;
69+
}
70+
result = Math.max(result, j - i);
71+
}
72+
return result;
73+
}
74+
}
4275
}

src/test/java/com/fishercoder/_1493Test.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,13 @@
88

99
public class _1493Test {
1010
private static _1493.Solution1 solution1;
11+
private static _1493.Solution2 solution2;
1112
private static int[] nums;
1213

1314
@BeforeClass
1415
public static void setup() {
1516
solution1 = new _1493.Solution1();
17+
solution2 = new _1493.Solution2();
1618
}
1719

1820
@Test
@@ -21,4 +23,16 @@ public void test1() {
2123
assertEquals(3, solution1.longestSubarray(nums));
2224
}
2325

26+
@Test
27+
public void test2() {
28+
nums = new int[]{1, 1, 0, 1};
29+
assertEquals(3, solution2.longestSubarray(nums));
30+
}
31+
32+
@Test
33+
public void test3() {
34+
nums = new int[]{0, 1, 1, 1, 0, 1, 1, 0, 1};
35+
assertEquals(5, solution2.longestSubarray(nums));
36+
}
37+
2438
}

0 commit comments

Comments
 (0)