5916. 转化数字的最小运算数
Posted lgz0921
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了5916. 转化数字的最小运算数相关的知识,希望对你有一定的参考价值。
题目链接:力扣
思路:bfs暴力搜索即可。每一种情况都搜一遍,已经搜过的值标记一下,不要重复搜。越界的值也不需要继续往下搜哦~~~(好久没写bfs了,手生了,忘记标记一开始的start了~~注意一下,一开始的start也要标记一下,要不后面必然也会造成重复搜~~~造成结果错误~~~)
上代码:
class Solution {
private val numMap = HashMap<Int, Boolean>()
private val queue = LinkedList<Int>()
private val dis = Array(1001) { 0 }
private fun check(x: Int, goal: Int): Boolean {
if (numMap.containsKey(x) || x != goal && (x < 0 || x > 1000)) {
return false
}
return true
}
private fun seek(topValue: Int, value: Int, goal: Int): Int {
if (check(value, goal)) {
if (value == goal) {
return dis[topValue] + 1
} else {
dis[value] = dis[topValue] + 1
queue.add(value)
numMap[value] = true
}
}
return -2
}
fun minimumOperations(nums: IntArray, start: Int, goal: Int): Int {
queue.add(start)
dis[start] = 0
numMap[start] = true
while (queue.isNotEmpty()) {
val topValue = queue.poll()
if (topValue == goal) {
return dis[topValue]
}
for (i in nums.indices) {
val operationAdd = seek(topValue, topValue + nums[i], goal)
if (operationAdd != -2) {
return operationAdd
}
val operationSub = seek(topValue, topValue - nums[i], goal)
if (operationSub != -2) {
return operationSub
}
val operationXor = seek(topValue, topValue xor nums[i], goal)
if (operationXor != -2) {
return operationXor
}
}
}
return -1
}
}
以上是关于5916. 转化数字的最小运算数的主要内容,如果未能解决你的问题,请参考以下文章