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

2998. make X and Y Equal number of operations

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

topic:

screenshot2024-01-10 afternoon5.12.21.png

Thought:

We will first x andNumber of operations 0 Put in a queue。Then,我们不断地从队列中取出当前的值andNumber of operations,Check whether the target value has reached the target value y。
if there is not,We will perform possible operation for this value,并将新值andNumber of operations加入队列中,Until finding the shortest path。

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
def minimumOperationsToMakeEqual(self, x: int, y: int) -> int:
# make用队列来进行Priority search
queue = deque([(x, 0)]) # (The current value, Number of operations)
visited = set() # Used to record the values ​​that have been accessed,Avoid repeated treatment

while queue:
current, steps = queue.popleft()
if current == y:
return steps
visited.add(current)

# Explore four operations
if current % 11 == 0 and current // 11 not in visited:
queue.append((current // 11, steps + 1))
if current % 5 == 0 and current // 5 not in visited:
queue.append((current // 5, steps + 1))
if current - 1 not in visited:
queue.append((current - 1, steps + 1))
if current + 1 not in visited:
queue.append((current + 1, steps + 1))

return -1 # 如果无法make x and y equal,Then return -1
  • Python
  • Dynamic planning
  • Priority search
  • Memory search

扫一扫,分享到微信

微信分享二维码
2997. Make an array or harmony K The minimum number of operations
3072. Allocate elements into two arrays II
目录
  1. 1. topic:
  2. 2. Thought:
  3. 3. Code:

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