前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >binarysearch Minimum Light Radius

binarysearch Minimum Light Radius

原创
作者头像
freesan44
修改2021-10-19 14:19:50
6770
修改2021-10-19 14:19:50
举报
文章被收录于专栏:freesan44freesan44

问题

You are given a list of integers nums representing coordinates of houses on a 1-dimensional line. You have 3 street lights that you can put anywhere on the coordinate line and a light at coordinate x lights up houses in x - r, x + r, inclusive. Return the smallest r required such that we can place the 3 lights and all the houses are lit up.

Constraints

n ≤ 100,000 where n is the length of nums

代码语言:txt
复制
Example 1
Input
nums = [3, 4, 5, 6]
Output
0.5
Explanation
If we place the lamps on 3.5, 4.5 and 5.5 then with r = 0.5 we can light up all 4 houses.

思路

根据最左二分法的模板逐步遍历

代码

  • 语言支持:Python3

Python3 Code:

代码语言:txt
复制
class Solution:
    def solve(self, nums):
        if len(nums) <= 3:
            return 0
        nums.sort()

        def possible(d):
            start = nums[0]
            end = start + d
            for i in range(3):
                index = bisect.bisect_right(nums, end)
                if index >= len(nums):
                    return True
                start = nums[index]
                end = start + d
            return False
        
        l, r = 0, nums[-1] - nums[0]
        while l <= r:
            mid = (l + r) // 2
            if possible(mid):
                r = mid - 1
            else:
                l = mid + 1
        return l / 2

复杂度分析

令 n 为数组长度。

  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(1)$

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

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