首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 2078. Two Furthest Houses With Different Colors

Leetcode 2078. Two Furthest Houses With Different Colors

作者头像
Tyan
发布2022-05-10 08:02:42
2350
发布2022-05-10 08:02:42
举报
文章被收录于专栏:SnailTyanSnailTyanSnailTyan

文章作者:Tyan 博客:noahsnail.com  |  CSDN  |  简书

1. Description

Two Furthest Houses With Different Colors
Two Furthest Houses With Different Colors

2. Solution

**解析:**Version 1,两层循环遍历,O(N^2)。

  • Version 1
class Solution:
    def maxDistance(self, colors: List[int]) -> int:
        distance = 0
        length = len(colors)
        for i in range(length):
            for j in range(i+1, length):
                if colors[i] != colors[j]:
                    distance = max(distance, j - i)
        return distance

**解析:**Version 2,贪心算法,从右往左找与左边第一个不同颜色的房子,从左往右找与右边第一个不同颜色的房子,取距离最大的一个,O(N)。

  • Version 2
class Solution:
    def maxDistance(self, colors: List[int]) -> int:
        distance = 0
        length = len(colors)
        for i in range(length-1, -1, -1):
            if colors[i] != colors[0]:
                distance = max(distance, i)
                break
        for i in range(length):
            if colors[i] != colors[length - 1]:
                distance = max(distance, length - 1 - i)
                break
        return distance

**解析:**Version 3,Version 2的另一个版本,通过一次循环完成,O(N)。

  • Version 3
class Solution:
    def maxDistance(self, colors: List[int]) -> int:
        distance = 0
        length = len(colors)
        for index, color in enumerate(colors):
            if color != colors[0]:
                distance = max(distance, index)
            if color != colors[length-1]:
                distance = max(distance, length - 1 - index)
        return distance

Reference

  1. https://leetcode.com/problems/two-furthest-houses-with-different-colors/
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-05-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. Description
  • 2. Solution
  • Reference
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档