Minimum Swaps to Group All 1's Together
Problem Descriptionβ
Visit LeetCode for the full problem description.
Solutionsβ
Solution 1: C# (Best: 204 ms)β
| Metric | Value |
|---|---|
| Runtime | 204 ms |
| Memory | 42.7 MB |
| Date | 2021-09-13 |
Solution
public class Solution {
public int MinSwaps(int[] data) {
int count = data.Where(x=> x==1).Count();
int left =0, right =0;
int curZeroes = 0;
int result = Int32.MaxValue;
while(right<data.Length)
{
if (data[right] == 0)
{
curZeroes++;
}
if(right-left+1>count)
{
if (data[left] == 0)
curZeroes--;
left++;
}
if(right-left+1==count)
{
result = Math.Min(result, curZeroes);
}
right++;
}
return result;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | To be analyzed | To be analyzed |