生死看淡不服就干,你不卷自然有人来卷你。切不可停下脚步。

题目
1、题目描述
街上有 n 栋房子整齐地排成一列,每栋房子都粉刷上了漂亮的颜色。给你一个下标从 0 0 0开始且长度为 n n n 的整数数组 c o l o r s colors colors ,其中 c o l o r s [ i ] colors[i] colors[i] 表示第 i i i 栋房子的颜色。
返回两栋 颜色不同 房子之间的 最大距离。
第 i i i 栋房子和第 j j j 栋房子之间的距离是 a b s ( i − j ) abs(i - j) abs(i−j) ,其中 a b s ( x ) abs(x) abs(x) 是 x x x 的绝对值。
示例:
输入:colors = [1,1,1,6,1,1,1]
输出:3
2、原题链接
解题报告
1、解题思路
(1)判断前后两个房子的颜色是否相同。
(2)如果颜色不同,更新距离。
2、解题方法
枚举
2、代码详解
int maxDistance(int* colors, int colorsSize){
int l, r, lcolor, rcolor;
l = 0;
lcolor = colors[0];
rcolor = colors[colorsSize-1];
for(int i = 1; i < colorsSize; ++i){
if(colors[i] != lcolor){
r = i;
}
}
int lans = r - l;
r = colorsSize-1;
for(int i = colorsSize-1; i >= 0; --i){
if(colors[i] != rcolor){
l = i;
}
}
int rans = r - l;
return lans > rans ? lans : rans;
}
小知识
可以用两层循环直接枚举所有情况。