• 【LeetCode】二分


    [475] Heaters [Easy]

    给你一排房子,一排加热器。找到能warm所有房子的最小加热器半径。

    思路就是对于每个房子,找离它最近的左右两台heater, 分别求距离。温暖这个房子的heater,肯定是离它最近的那台。对于所有的房子求这个距离,然后取他们的最大值。时间复杂度O(N), 空间复杂度O(1)

     1 /*
     2  * 思路就是对于每个房子,找离它最近的左右两台heater, 分别求距离。
     3  * 温暖这个房子的heater,肯定是离它最近的那台。
     4  * 对于所有的房子求这个距离,然后取他们的最大值
     5  * 时间复杂度O(N), 空间复杂度O(1)
     6  * Wanying 2017/03/16
     7 */
     8 
     9 class Solution {
    10 public:
    11     int findRadius(vector<int>& houses, vector<int>& heaters) {
    12         sort(heaters.begin(), heaters.end());
    13         int ans = INT_MIN;
    14         for (auto ele : houses) {
    15             int distance = INT_MAX;
    16             auto iter = lower_bound(heaters.begin(), heaters.end(), ele);
    17             if (iter == heaters.begin()) {
    18                 distance = min(distance, abs(*iter - ele));
    19             } else if (iter == heaters.end()) {
    20                 iter--;
    21                 distance = min(distance, abs(ele - *iter));
    22             } else {
    23                 distance = min(abs(*iter - ele), abs(*(iter - 1) - ele));
    24             }
    25             ans = max(ans, distance);
    26         }
    27         return ans;
    28     }
    29 };
    View Code
  • 相关阅读:
    2014第16周六
    2014第16周五
    2014第16周四
    2014第16周三CSS布局再学习摘录
    2014第16周二
    2014第16周一
    2014第15周日
    2014第15周六
    2014第15周五
    SDN:软件定义网络
  • 原文地址:https://www.cnblogs.com/zhangwanying/p/6561777.html
Copyright © 2020-2023  润新知