正向双指针
有点麻烦,但是能通过,先提交一下,待我学习一下其他的解法再来提交
这个里面不用对opNum
进行计数,可以利用left
和right
的位置计算出来左右两边的长度,可以省略一些,这里我就不重新写了
func minOperations(nums []int, x int) int {
if nums[0] > x && nums[len(nums)-1] > x {
return -1
}
left, right := -1, len(nums) - 1
opNum, minNum := 0, -1
sum := 0
for left < right {
left++
sum += nums[left]
opNum++
if sum > x {
sum -= nums[left]
left--
opNum--
break
} else if sum == x {
minNum = opNum
break
}
}
for left < right {
for sum >= x && left >= 0 {
sum -= nums[left]
left--
opNum--
if sum == x && (opNum < minNum || minNum == -1) {
minNum = opNum
}
}
sum += nums[right]
right--
opNum++
if sum == x && (opNum < minNum || minNum == -1) {
minNum = opNum
}
}
return minNum
}
逆向思维
可以转换成求【数组总和-x 】为目标的最长子数组
func minOperations(nums []int, x int) int {
sum := 0
for _, n := range nums {
sum += n
}
x = sum - x
left := 0
sum = 0
ans := -1
for right, v := range nums {
sum += v
for left <= right && sum > x {
sum -= nums[left]
left++
}
if sum == x {
ans = max(ans, right - left + 1)
}
}
if ans < 0 {
return -1
}
return len(nums) - ans
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
参考
1658. 将 x 减到 0 的最小操作数 - 力扣(Leetcode)
两种写法:逆向思维/直接双指针(Python/Java/C++/Go)
标签:操作数,right,nums,sum,opNum,1658,leetcode,minNum,left From: https://www.cnblogs.com/wudanyang/p/17033790.html