概述
给出一个数组,代表房屋的颜色。所以array[i]代表索引为i的房子的颜色。目标是找到两个最远的不同颜色的房子。
如果不存在这样的索引,则返回-1
例子1
Input: intervals = [2,2,2,1,2,2]
Output: 3
Explanation: House at index 0 and house at index 3 is of different colors
例子2
Input: intervals = [1, 2 ,3, 1, 2]
Output: 2
Explanation: House at index 0 and house at index 4 is of different colors
下面是我们可以采取的方法。
- 其中一个房子要么在第0个索引,要么在第n-1个索引,n是数组的长度。
- 我们可以先假设第0个索引的房子在解决方案中,然后计算出
- 接下来我们可以假设第n-1个索引的房子在解决方案中,然后计算出
程序
以下是相同的程序。
package main
import "fmt"
func maxDistance(colors []int) int {
lenColors := len(colors)
if lenColors == 0 || lenColors == 1 {
return 0
}
maxDiff := 0
leftColor := colors[0]
rightColor := colors[lenColors-1]
for i := 1; i < lenColors; i++ {
if colors[i] != leftColor {
maxDiff = i
}
}
for i := lenColors - 2; i >= 0; i-- {
if colors[i] != rightColor {
diff := lenColors - i - 1
if diff > maxDiff {
maxDiff = diff
}
}
}
return maxDiff
}
func main() {
output := maxDistance([]int{2, 2, 2, 1, 2, 2})
fmt.Println(output)
output = maxDistance([]int{1, 2, 3, 1, 2})
fmt.Println(output)
}
输出
4
-1
注意: 请查看我们的Golang高级教程。这个系列的教程是精心设计的,我们试图用例子涵盖所有的概念。本教程是为那些希望获得专业知识和对Golang有扎实了解的人准备的 -Golang高级教程
如果你有兴趣了解如何在Golang中实现所有设计模式。如果是的话,那么这篇文章就是为你准备的--所有设计模式 Golang
The postTwo furthest houses with different colors in Go (Golang)appeared first onWelcome To Golang By Example.