zoukankan      html  css  js  c++  java
  • 【数据结构】供暖 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

  • 相关阅读:
    eclipse常用的快捷键
    如何保留小数点后N位?
    EditText设置/隐藏光标位置、选中文本和获取/清除焦点(转)
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo异常(转)
    STL优先队列 hdu1896
    工作排序问题 poj2376
    STL存储邻接表
    二叉树的遍历
    快速排序
    并查集 并查集来判断是否存在环路
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/15057235.html
Copyright © 2011-2022 走看看