题目来源:
leetcode题目,网址:2078. 两栋颜色不同且距离最远的房子 - 力扣(LeetCode)
解题思路:
遍历数组,找到每个颜色的首次出现位置及其与该颜色最远的颜色不同房子的距离,最后返回最大值即可。
解题代码:
class Solution {
public int maxDistance(int[] colors) {
int res=0;
Set<Integer> set=new HashSet<>();
for(int i=0;i<colors.length;i++){
if(set.contains(colors[i])){
continue;
}
set.add(colors[i]);
for(int j=colors.length-1;j>i;j--){
if(colors[j]!=colors[i]){
res=Math.max(j-i,res);
break;
}
}
}
return res;
}
}
总结:
官方题解也是暴力查找。评论区有人指出最长距离要么是与第一个元素不同的最右边元素,要么是与最后一个元素不同的最左边元素。