class Solution { public: int findRadius(vector<int>& houses, vector<int>& heaters) { int res=0; int len1=houses.size(); int len2=heaters.size(); sort(houses.begin(),houses.end());//先排序 sort(heaters.begin(),heaters.end()); int index_sta=0; int index_end=len2-1; for(int i=0;i<len1/2;i++)//对于第一个房屋和最后一个房屋,检测各自前后两个供暖器 { while(index_sta<len2-1&&houses[i]-heaters[index_sta+1]>0) index_sta++; while(index_end>0&&houses[len1-1-i]-heaters[index_end-1]<0) index_end--; int temp1;//取前后供暖器位置最近的 if(index_sta==len2-1) temp1=abs(houses[i]-heaters[index_sta]); else temp1=min(abs(houses[i]-heaters[index_sta]),abs(houses[i]-heaters[index_sta+1])); int temp2; if(index_end==0) temp2=abs(houses[len1-1-i]-heaters[index_end]); else temp2=min(abs(houses[len1-1-i]-heaters[index_end]),abs(houses[len1-1-i]-heaters[index_end-1])); if(max(temp1,temp2)>res)//取两个位置里最大的 res=max(temp1,temp2); } return res; } };
分析:
有点恶心。
原文地址:https://www.cnblogs.com/CJT-blog/p/10820022.html
时间: 2024-10-10 02:26:20