leetcode update

This commit is contained in:
gameloader 2024-10-15 12:34:23 +08:00
parent ab244c4817
commit d85bfc486c

View File

@ -15634,3 +15634,44 @@ public:
} }
}; };
``` ```
## day231 2024-10-15
### 2938. Separate Black and White Balls
There are n balls on a table, each ball has a color black or white.
You are given a 0-indexed binary string s of length n, where 1 and 0 represent black and white balls, respectively.
In each step, you can choose two adjacent balls and swap them.
Return the minimum number of steps to group all the black balls to the right and all the white balls to the left.
![101581cgwXkBIJs6](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/101581cgwXkBIJs6.png)
### 题解
本题起初想到可以遍历一遍数组统计0的个数再遍历数组将前面的1和后面的0交换直到到达0的个数的位置。但这样好像麻烦了一些统计0的个数其实没有必要直接使用双指针分别从首尾开始遍历数组尾指针遇到的0和首指针遇到的1交换直到两个指针相遇即可。原因在于尾指针每次遇到0就将其和1交换则尾指针指向位置之后的数组可以确保是全1的同理首指针之前的数组可以确保是全0的。二者相遇时相遇位置之后的数组为全1之前的为全0就已经满足题目条件了。
遍历过程中尾指针遇到0停下移动首指针直到遇到1计算二者距离并加和到结果中继续移动尾指针直到头尾相遇结束。
### 代码
```cpp
class Solution {
public:
long long minimumSteps(string s) {
long long int head = 0;
long long int tail = s.size()-1;
long long int result = 0;
while (tail > head){
while(s[tail] != '0' && tail > head){
tail--;
}
while(s[head] != '1' && head < tail){
head++;
}
result += tail-head;
tail--;
head++;
}
return result;
}
};
```