From d85bfc486cc5270e17f4efa886e5a8c3fc936435 Mon Sep 17 00:00:00 2001 From: gameloader Date: Tue, 15 Oct 2024 12:34:23 +0800 Subject: [PATCH] leetcode update --- content/posts/leetcode.md | 41 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/content/posts/leetcode.md b/content/posts/leetcode.md index 463e931..6cad86d 100644 --- a/content/posts/leetcode.md +++ b/content/posts/leetcode.md @@ -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; + } +}; +``` +