• 【数据结构】供暖 heaters


    供暖 heaters

    给出位于同一个水平线上的房屋houses和供暖器heaters的位置。要求设计一个具有最小加热半径的供暖器可以向所有房屋供暖

    houses = [1,2,3], heaters = 【2】
    1
    
    houses = [1,2,3,4], heaters = [1,4]
    1  
    

    思路

    因为每个heater的加热半径是一样的,所以求出每一个house到距离它最近的heater的距离,然后在这个距离中找到最大的那个,就可以满足我们的目标。

    public int findRadius(int[] houses, int[] heaters) {
            Arrays.sort(heaters);
            int ans = 0;
            for (int i = 0; i < houses.length ; i++) {
                int x = houses[i];
                int j = binarysearch01(heaters,x);
                 // left present the distance between houses[i] and  the first heater index bigger than houses[i],
                // if not exist the first bigger element ,
                // left present the distance between houses[i] and the last heater index small than houses[i] .
                int left =Math.abs(x-heaters[j]);
                // right present the distance between house[i] and the former heater.
                // when j equal zero,heater[j-1] is illegal.So choose the bigger one.
                ans = Math.max(ans,Math.min(left,right));
            }
            return ans;
        }
    
        // find index of the first element bigger than x
        // if exists return index, OR finally return the last index of element that smaller than x.
        public int binarysearch01(int[] arr ,int x){
            int head =0;
            int tail = arr.length-1;
            int mid =0;
            while (head<tail){
                mid = (head+tail)>>1;
                if (arr[mid]>=x){
                    tail = mid;
                }
                else{
                    head = mid+1;
                }
            }
            return head;
        }
    

    Tag

    binary search

  • 相关阅读:
    C#文件读写常用类介绍
    C#实现注销、重启和关机代码
    Mybatis学习---基础知识考核
    Linux操作系统各版本ISO镜像下载
    Java学习---JDK的安装和配置
    Java学习---基础知识学习
    Java学习---常见的模式
    Java实例---黑白五子棋[单机版]
    Java实例---简单的超市管理系统
    Java实例---简单的个人管理系统
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/15057235.html
Copyright © 2020-2023  润新知