Heaters(C++供暖器)

解题思路:

首先吐槽下,原来给定的不是排序好的,按照我的思路还是要先排序的,哈哈哈,其实有点贪心算法的味道

(1)首先将两个都排序

(2)假设存在两个供暖器,i,j. 记落在ij之间距离i小于等于ij供暖器一半距离的房屋集合为H={h1,h2,...hn}

(3)剩下的就是距离j大于ij供暖器一半距离的房屋集合为G={g1,g2,...gm},设j到G的最大距离为j_front_max

(4)记i之前的供暖器为k,那么按照(3)求得i_front_max

(5)记i到H的最大距离为i_back_max

(6)供暖器i的供暖半径(贪心策略)i_max = max{i_front_max,i_back_max}

class Solution {
public:
    int findRadius(vector<int>& houses, vector<int>& heaters) {
    	sort(houses.begin(), houses.end());
        sort(heaters.begin(), heaters.end());
		
        int i=0,j=0,max=0;
		while(i<heaters.size()) {
			while(j<houses.size() && houses[j]<=heaters[i]) {
				if (heaters[i]-houses[j]>max) {
					max = heaters[i]-houses[j];
				}
				j++;
			}
			
			if (j<houses.size()) {
				if (i+1<heaters.size()) {
					while(j<houses.size() && houses[j]>heaters[i]) {
						if (houses[j]<=heaters[i+1]) {
							if (houses[j]-heaters[i] <= heaters[i+1]-houses[j]) {
								if (houses[j]-heaters[i]>max) {
									max = houses[j]-heaters[i];
								}
								j++;
							} else {
								i++;
								break;
							}
						} else {
							i++;
							break;
						}
					}

				} else {
					while(j<houses.size() && houses[j]>heaters[i]) {
						if (houses[j]-heaters[i]>max) {
							max = houses[j]-heaters[i];
						}
						j++;	
					}
					i++;
				}
			} else break;
			
		} 
		return max;
    }
};
发布了264 篇原创文章 · 获赞 272 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105504187