A swap is defined as taking two distinct positions in an array and swapping the values in them.
A circular array is defined as an array where we consider the first element and the last element to be adjacent.
Given a binary circular array nums
, return the minimum number of swaps required to group all 1
's present in the array together at any location.
Example 1:
Input: nums = [0,1,0,1,1,0,0] Output: 1 Explanation: Here are a few of the ways to group all the 1's together: [0,0,1,1,1,0,0] using 1 swap. [0,1,1,1,0,0,0] using 1 swap. [1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array). There is no way to group all 1's together with 0 swaps. Thus, the minimum number of swaps required is 1.
Example 2:
Input: nums = [0,1,1,1,0,0,1,1,0] Output: 2 Explanation: Here are a few of the ways to group all the 1's together: [1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array). [1,1,1,1,1,0,0,0,0] using 2 swaps. There is no way to group all 1's together with 0 or 1 swaps. Thus, the minimum number of swaps required is 2.
Example 3:
Input: nums = [1,1,0,0,1] Output: 0 Explanation: All the 1's are already grouped together due to the circular property of the array. Thus, the minimum number of swaps required is 0.
Constraints:
1 <= nums.length <= 105
nums[i]
is either0
or1
.
思路:这题跟 Minimum Swaps to Group All 1‘s Together 不一样的地方就是循环数组的情况,前后怎么连起来,解决方法就是append一个一模一样的数组,然后connect的最大,应该就在里面,这样代码只需加一点点就可以work。
class Solution {
public int minSwaps(int[] nums) {
int n = nums.length;
int count = 0;
for(int num: nums) {
if(num == 1) {
count++;
}
}
int[] A = new int[n * 2];
for(int i = 0; i < A.length; i++) {
A[i] = nums[i % n];
}
int j = 0;
int curcount = 0;
int max = 0;
for(int i = 0; i < A.length; i++) {
while(j < A.length && j - i < count) {
if(A[j] == 1) {
curcount++;
}
j++;
}
max = Math.max(max, curcount);
if(j == A.length) {
break;
}
// move i;
if(A[i] == 1) {
curcount--;
}
}
return count - max;
}
}