@@ -60,13 +60,45 @@ Thus, the minimum number of swaps required is 0.
60
60
### ** Python3**
61
61
62
62
``` python
63
-
63
+ class Solution :
64
+ def minSwaps (self , nums : List[int ]) -> int :
65
+ cnt = nums.count(1 )
66
+ n = len (nums)
67
+ s = [0 ] * ((n << 1 ) + 1 )
68
+ for i in range (n << 1 ):
69
+ s[i + 1 ] = s[i] + nums[i % n]
70
+ mx = 0
71
+ for i in range (n << 1 ):
72
+ j = i + cnt - 1
73
+ if j < (n << 1 ):
74
+ mx = max (mx, s[j + 1 ] - s[i])
75
+ return cnt - mx
64
76
```
65
77
66
78
### ** Java**
67
79
68
80
``` java
69
-
81
+ class Solution {
82
+ public int minSwaps (int [] nums ) {
83
+ int cnt = 0 ;
84
+ for (int v : nums) {
85
+ cnt += v;
86
+ }
87
+ int n = nums. length;
88
+ int [] s = new int [(n << 1 ) + 1 ];
89
+ for (int i = 0 ; i < (n << 1 ); ++ i) {
90
+ s[i + 1 ] = s[i] + nums[i % n];
91
+ }
92
+ int mx = 0 ;
93
+ for (int i = 0 ; i < (n << 1 ); ++ i) {
94
+ int j = i + cnt - 1 ;
95
+ if (j < (n << 1 )) {
96
+ mx = Math . max(mx, s[j + 1 ] - s[i]);
97
+ }
98
+ }
99
+ return cnt - mx;
100
+ }
101
+ }
70
102
```
71
103
72
104
### ** TypeScript**
@@ -80,13 +112,66 @@ function minSwaps(nums: number[]): number {
80
112
for (let i = m ; i < m + n ; i ++ ) {
81
113
let prev = nums [i - m ];
82
114
let post = nums [i % n ];
83
- cnt += ( post - prev ) ;
115
+ cnt += post - prev ;
84
116
ans = Math .max (cnt , ans );
85
117
}
86
118
return m - ans ;
119
+ }
120
+ ```
121
+
122
+ ### ** C++**
123
+
124
+ ``` cpp
125
+ class Solution {
126
+ public:
127
+ int minSwaps(vector<int >& nums) {
128
+ int cnt = 0;
129
+ for (int& v : nums) cnt += v;
130
+ int n = nums.size();
131
+ vector<int > s((n << 1) + 1);
132
+ for (int i = 0; i < (n << 1); ++i) s[ i + 1] = s[ i] + nums[ i % n] ;
133
+ int mx = 0;
134
+ for (int i = 0; i < (n << 1); ++i)
135
+ {
136
+ int j = i + cnt - 1;
137
+ if (j < (n << 1)) mx = max(mx, s[ j + 1] - s[ i] );
138
+ }
139
+ return cnt - mx;
140
+ }
87
141
};
88
142
```
89
143
144
+ ### **Go**
145
+
146
+ ```go
147
+ func minSwaps(nums []int) int {
148
+ cnt := 0
149
+ for _, v := range nums {
150
+ cnt += v
151
+ }
152
+ n := len(nums)
153
+ s := make([]int, (n<<1)+1)
154
+ for i := 0; i < (n << 1); i++ {
155
+ s[i+1] = s[i] + nums[i%n]
156
+ }
157
+ mx := 0
158
+ for i := 0; i < (n << 1); i++ {
159
+ j := i + cnt - 1
160
+ if j < (n << 1) {
161
+ mx = max(mx, s[j+1]-s[i])
162
+ }
163
+ }
164
+ return cnt - mx
165
+ }
166
+
167
+ func max(a, b int) int {
168
+ if a > b {
169
+ return a
170
+ }
171
+ return b
172
+ }
173
+ ```
174
+
90
175
### ** ...**
91
176
92
177
```
0 commit comments