avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

1653. The minimum number of times to balance the string balance

  2024-01-01        
字数统计: 227字   |   阅读时长: 1min

topic:

2023-03-07.png
1653. The minimum number of times to balance the string balance.md

Thought:

img_1.png
ask:Why if-else Write (c - ‘a’) * 2 - 1 It will be much faster?

answer:CPU I encounter a branch(Condition jump instruction)Which branch of the code will be predicted when the code is executed,If the prediction is correct,
CPU It will continue to execute the program in accordance with the predicted path。But if the prediction fails,CPU You need to roll back the previous instructions and load the correct instructions,To ensure the correctness of the program execution。

For the data of this question,character ‘a’ and ‘b’ It can be considered to appear random,In this case, the branch prediction will be available 50% Probability failure。
失败导致的回滚and加载操作需要消耗额外的 CPU cycle,If the branch can be removed at a smaller price,The situation of this question can inevitably bring efficiency improvement。

Notice:This optimization method often reduces readability,It’s best not to use in business code。

Code:

1
2
3
4
5
6
7
8
9
class Solution:
def minimumDeletions(self, s: str) -> int:
ans = delete = s.count('a')
for c in s:
delete -= 1 if c == 'a' else -1
if delete < ans: # Manually min It will be much faster
ans = delete
return ans

  • Python
  • answer

扫一扫,分享到微信

微信分享二维码
1604Warn alert person who uses the same employee card within one hour One question daily
1590.Make the array and energyPDivide
目录
  1. 1. topic:
  2. 2. Thought:
  3. 3. Code:

150 篇 | 131.7k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号