当前位置: 首页 > news >正文

LeetCode100122. 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.

Example 1:

Input: s = “101”
Output: 1
Explanation: We can group all the black balls to the right in the following way:

  • Swap s[0] and s[1], s = “011”.
    Initially, 1s are not grouped together, requiring at least 1 step to group them to the right.
    Example 2:

Input: s = “100”
Output: 2
Explanation: We can group all the black balls to the right in the following way:

  • Swap s[0] and s[1], s = “010”.
  • Swap s[1] and s[2], s = “001”.
    It can be proven that the minimum number of steps needed is 2.
    Example 3:

Input: s = “0111”
Output: 0
Explanation: All the black balls are already grouped to the right.

Constraints:

1 <= n == s.length <= 105
s[i] is either ‘0’ or ‘1’.

二、题解

class Solution {
public:long long minimumSteps(string s) {int n = s.length();//记录0的位置vector<int> zeroIndex;for(int i = 0;i < n;i++){if(s[i] == '0') zeroIndex.push_back(i);}long long res = 0;int front = 0;for(int i = 0;i < zeroIndex.size();i++){res += zeroIndex[i] - front;front++;}return res;}
};
http://www.lryc.cn/news/235863.html

相关文章:

  • 系列二十六、idea安装javap -c
  • nginx 如何根据IP做限流,以及 nginx 直接返回 json 格式数据
  • C语言链式栈
  • 【Go入门】 Go的http包详解
  • 解决k8s node节点报错: Failed to watch *v1.Secret: unknown
  • 日志维护库:loguru
  • 【Go入门】 Go如何使得Web工作
  • 汽车虚拟仿真视频数据理解--CLIP模型原理
  • 【Web】Ctfshow SSTI刷题记录1
  • 【广州华锐互动】VR可视化政务服务为公众提供更直观、形象的政策解读
  • 音视频项目—基于FFmpeg和SDL的音视频播放器解析(七)
  • Sql Server 2017主从配置之:发布订阅
  • 聊聊logback的EvaluatorFilter
  • 解决vue 部分页面缓存,部分页面不缓存的问题
  • 修完这个 Bug 后,MySQL 性能提升了 300%
  • 【C/PTA】数组进阶练习(二)
  • Mysql MMM
  • GDPU 数据结构 天码行空10
  • CD36 ; + Lectin;
  • Git 分支管理
  • Vue23全局事件总线
  • GEM5 Garnet DVFS / NoC DVFS教程:ruby.clk_domain ruby.voltage_domain
  • java命令 jmap 堆参数分析
  • OpenCV C++ 图像处理实战 ——《OCR字符识别》
  • 在MySQL中创建新的数据库,可以使用命令,也可以通过MySQL工作台
  • 2311rust到31版本更新
  • 【Python百宝箱】视觉算法秀:Python图像处理舞台上的巅峰对决
  • Flutter 中在单个屏幕上实现多个列表
  • YOLOv8 加持 MobileNetv3,目标检测新篇章
  • .gitignore 文件——如何在 Git 中忽略文件和文件夹详细教程