所以我试图通过做一些算法挑战来学习围棋,我目前正在做的那个叫做几乎递增序列。
该指令如下所示:
给定一个整数序列作为数组,确定是否可以通过从数组中删除不超过一个元素来获得严格递增的序列。
- 对于
sequence = [1, 3, 2, 1]
,输出应该是almostIncreasingSequence(sequence) = false
;
此数组中没有一个元素可以删除以获得严格递增的序列。
- 对于
sequence = [1, 3, 2]
,输出应该是almostIncreasingSequence(sequence) = true
.
我们可以从数组中删除 3 以获得严格递增的序列 [1, 2]。或者,我们可以删除 2 以获得严格递增的序列 [1, 3]。
如果可以从数组中删除一个元素以获得严格递增的序列,则该函数必须返回 true,否则返回 false。
我已经在打字稿中完成了这个,这并不难。但是我试图用 Go 再次编写它,但我发现避免 Go 中的错误有点棘手index out of range
。这是我到目前为止的代码:
func almostIncreasingSequence(a []int) bool {
var count int = 0
for i := 0; i < len(a); i++ {
if a[i] <= a[i-1] {
count++
if (a[i] <= a[i-2]) && (a[i+1] <= a[i-1]) {
return false
}
}
}
return count <= 1
}
这就是我从字面上转换我在 Typescript 中写的内容的内容,它可以很好地与 Typescript 一起使用,但正如您从我的 Go 代码中很容易注意到的那样index out of range
当它迭代时发生错误时,if a[i] <= a[i-1]
.
有什么技巧可以比较索引i
和i - 1
的元素,或者i + 1
在 Go 中编写代码时避免index out of range
错误?
提前感谢!
这不是一个把戏。您正在从0
(第一个元素)循环到数组的长度减去 1 或上限。当i == len(a) - 1
时,a[i+1]
将超过数组的长度。如果其中只有 3 个项目,它们的索引将是0
、1
、2
。len(a)
给你3
.i < len(a)
导致0
到2
。
您还在第一次迭代中减去i
,这基本上是询问编译器if a[0] <= a[-1]
这导致a[-1]
超出数组的边界。你用a[i] <= a[i-2]
再次这样做.
我相当确定你只需要这样的东西:
func almostIncreasingSequence(a []int) bool {
count := 0 // := is shorthand. So long as it is within a func it is basically equiv of var. It also infers the type.
l := len(a) - 1
for i := 0; i < l; i++ {
if a[i] > a[i+1] {
count++
}
}
r := count <= 1
fmt.Println(a, r)
return r
}
结果:
[1 3 2 1] false
[1 3 2] true
https://play.golang.org/p/8d_3a_PMM2C
如果性能很重要并且阵列可能很大,请添加计数检查:
if a[i] > a[i+1] {
count = count + 1
if(count > 1) {
return false;
}
}
它在 JavaScript 中工作的原因是由于如何处理Undefined
。
console.log(1 < undefined)
console.log(0 < undefined)
const array = []
console.log(array[0] < 0)
console.log(array[-1] < 0)
console.log(array[9999] < 0)
由于它所设计的地形,这是一种令人难以置信的宽容语言。