题目描述:
街上有 n 栋房子整齐地排成一列,每栋房子都粉刷上了漂亮的颜色。给你一个下标从 0 开始且长度为 n 的整数数组 colors ,其中 colors[i] 表示第 i 栋房子的颜色。
返回 两栋 颜色 不同 房子之间的 最大 距离。
第 i 栋房子和第 j 栋房子之间的距离是 abs(i - j) ,其中 abs(x) 是 x 的绝对值。
题目链接:2078. 两栋颜色不同且距离最远的房子 - 力扣(LeetCode)
解题思路:
对于一种颜色来说,其他的颜色都是不同的。
比如 [ 1 , 8, 3, 8, 3]
对于 '1' 这个颜色,就是[ 1 , 0, 0, 0, 0],最大距离为4
对于'8' 这个颜色,就是[ 0 , 8, 0, 0, 0],最大距离为3
对于'3' 这个颜色,就是[ 0 , 0, 3, 0, 3],最大距离为4
所以只需要遍历O(n),查找从头开始与第一个元素不同的最远距离 比较 从尾开始与最后一个元素不同的最远距离,哪个更大即是答案。
代码如下:
cpp
class Solution {
public:
int maxDistance(vector<int>& colors) {
int length = colors.size();
int ans1 = 0;
int ans2 = 0;
for ( int i = 1; i < length; ++ i ){
if ( colors[ 0 ] != colors[ i ] ){
ans1 = i;
}
}
-- length;
for ( int i = length - 1; i >= 0; -- i ){
if ( colors[ length ] != colors[ i ] ){
ans2 = i;
}
}
if ( ans1 ){
return ans1 > length - ans2 ? ans1 : length - ans2;
}else{
return 0;
}
}
};