forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1151.java
44 lines (43 loc) · 1.2 KB
/
_1151.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.fishercoder.solutions;
public class _1151 {
public static class Solution1 {
/**
* My completely original solution on 11/4/2021.
* Typical sliding window problem/solution
*/
public int minSwaps(int[] data) {
int oneCount = 0;
for (int d : data) {
if (d == 1) {
oneCount++;
}
}
if (oneCount <= 1) {
return 0;
}
int left = 0;
int right = 0;
int ones = 0;
int zeroes = 0;
int minSwaps = data.length;
while (right < data.length) {
if (data[right] == 1) {
ones++;
} else {
zeroes++;
}
if (ones + zeroes == oneCount) {
minSwaps = Math.min(minSwaps, zeroes);
if (data[left] == 1) {
ones--;
} else {
zeroes--;
}
left++;
}
right++;
}
return minSwaps;
}
}
}