- Leetcode 3377. Digit Operations to Make Two Integers Equal
- 1. 解题思路
- 2. 代码实现
- 题目链接:3377. Digit Operations to Make Two Integers Equal
1. 解题思路
这一题的核心思路属于路径遍历问题,我们使用一个堆排来控制最优路径的选择。
我们首先全局地给出10000以内的全部素数,然后我们考察当前数据所能获得的全部合法的操作结果,然后用堆排存入之后按照cost进行遍历,直到所有的结果都被遍历过或者找到目标值m为止。
2. 代码实现
给出python代码实现如下:
def get_primes(n):
primes = set()
status = [0 for _ in range(n+1)]
for i in range(2, n+1):
if status[i] == 1:
continue
primes.add(i)
for j in range(i, n+1, i):
status[j] = 1
return primes
PRIMES = get_primes(10000)
class Solution:
def minOperations(self, n: int, m: int) -> int:
if n in PRIMES:
return -1
l = len(str(n))
seen = set()
q = [(n, n)]
while q:
cost, n = heapq.heappop(q)
if n in seen:
continue
if n == m:
return cost
seen.add(n)
sn, delta = str(n)[::-1], 1
for digit in sn:
if digit != "0" and n-delta not in PRIMES:
heapq.heappush(q, (cost + n-delta, n-delta))
if digit != "9" and n+delta not in PRIMES:
heapq.heappush(q, (cost + n+delta, n+delta))
delta *= 10
return -1
提交代码评测得到:耗时846ms,占用内存19.6MB。