-
Notifications
You must be signed in to change notification settings - Fork 0
/
1151. Minimum Swaps to Group All 1's Together.cpp
124 lines (107 loc) · 2.7 KB
/
1151. Minimum Swaps to Group All 1's Together.cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// ***
//
// Given a binary array data, return the minimum number of swaps required to group all 1’s present in the array together
// in any place in the array.
//
//
// Example 1:
//
// Input: data = [1,0,1,0,1]
// Output: 1
// Explanation:
// There are 3 ways to group all 1's together:
// [1,1,1,0,0] using 1 swap.
// [0,1,1,1,0] using 2 swaps.
// [0,0,1,1,1] using 1 swap.
// The minimum is 1.
//
//
// Example 2:
//
// Input: data = [0,0,0,1,0]
// Output: 0
// Explanation:
// Since there is only one 1 in the array, no swaps needed.
//
//
// Example 3:
//
// Input: data = [1,0,1,0,1,0,0,1,1,0,1]
// Output: 3
// Explanation:
// One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1].
//
//
// Example 4:
//
// Input: data = [1,0,1,0,1,0,1,1,1,0,1,0,0,1,1,1,0,0,1,1,1,0,1,0,1,1,0,0,0,1,1,1,1,0,0,1]
// Output: 8
//
// ***
class Solution {
public:
int minSwaps(vector<int>& data) {
int totalOnes = accumulate(data.begin(), data.end(), 0);
int res = INT_MAX;
int numOnes = 0;
int left = 0, right = 0;
while (right < data.size()) {
int num = data[right++];
if (num == 1) {
++numOnes;
}
while (right - left > totalOnes) {
int num = data[left++];
if (num == 1) {
--numOnes;
}
}
if (right - left == totalOnes) {
res = min(res, totalOnes - numOnes);
}
}
return res;
}
};
// Same idea.
class Solution {
public:
int minSwaps(vector<int>& data) {
int totalOnes = accumulate(data.begin(), data.end(), 0);
int res = INT_MAX;
vector<int> window(2, 0);
int left = 0, right = 0;
while (right < data.size()) {
int num = data[right++];
++window[num];
while (window[0] + window[1] > totalOnes) {
int num = data[left++];
--window[num];
}
if (window[0] + window[1] == totalOnes) {
res = min(res, window[0]);
}
}
return res;
}
};
// Same idea.
class Solution {
public:
int minSwaps(vector<int>& data) {
int totalOnes = accumulate(data.begin(), data.end(), 0);
int res = INT_MAX;
vector<int> window(2, 0);
int left = 0, right = 0;
while (right < data.size()) {
int num = data[right++];
++window[num];
while (window[0] + window[1] == totalOnes) {
res = min(res, window[0]);
int num = data[left++];
--window[num];
}
}
return res == INT_MAX ? 0 : res;
}
};