LeetCode 475. Heaters
阿新 • • 發佈:2018-05-31
span begin 最小值 時間 min clas radius fin div
最大化最小值的問題。
方法一:直接做,順便復習一下叠代器和lower_bound的用法。
class Solution { public: int findRadius(vector<int>& houses, vector<int>& heaters) { sort(houses.begin(),houses.end()); sort(heaters.begin(),heaters.end()); int maxdis=0; for (int i=0;i<houses.size();++i){if (houses[i]<=heaters[0]){ maxdis=max(heaters[0]-houses[i],maxdis); }else if (houses[i]>=heaters[heaters.size()-1]){ maxdis=max(houses[i]-heaters[heaters.size()-1],maxdis); }else{ auto pos=lower_bound(heaters.begin(),heaters.end(),houses[i]);int tmp=min(houses[i]-*(--pos), *pos-houses[i]); maxdis = max(tmp,maxdis); } } return maxdis; } };
方法二:分別計算每個house左面和右面距離最近的heater。時間復雜度比上述要低。學習一下 *max_element 和 *min_element 的用法。
class Solution { public: int findRadius(vector<int>& houses, vector<int>& heaters) { int m=houses.size(), n=heaters.size(); sort(houses.begin(),houses.end()); sort(heaters.begin(),heaters.end()); vector<int> res(m,INT_MAX); for (int i=0,j=0;i<m&&j<n;){ if (houses[i]<=heaters[j]){res[i] = heaters[j]-houses[i]; ++i;} else ++j; } for (int i=m-1,j=n-1;i>=0&&j>=0;){ if (houses[i]>=heaters[j]){res[i] = min(houses[i]-heaters[j],res[i]); --i;} else --j; } return *max_element(res.begin(),res.end()); } };
LeetCode 475. Heaters