Leet Code - 475. Heaters

포타토·2020년 5월 25일
1

알고리즘

목록 보기
75/76

예제: Heaters

문제
Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.

Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.

So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.

Note:

  1. Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
  2. Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
  3. As long as a house is in the heaters' warm radius range, it can be warmed.
  4. All the heaters follow your radius standard and the warm radius will the same.

Example 1:

Input: [1,2,3],[2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.

Example 2:

Input: [1,2,3,4],[1,4]
Output: 1
Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.

풀이

개인적으로 참 어려웠던 문제이다.

2중 for문을 돌려서 '집과 히터의 최소거리들의 최대값'을 구하면 바로 풀리지만, 당연히 time limit exceeded에 걸린다.

그래서 필자는 2중 for문에서 살짝 틀어 주었다.
바로 index를 저장해서, 두 번재 for문을 0부터 돌지 않고 index 위치부터 시작하도록 하는 것.

뭔가 되게 허접스런 방법 같지만, 나름 많이 고민했다.
easy 난이도지만, 점점 만만치가 않은것이 느껴진다.

전체적인 소스코드는 아래와 같다.

소스 코드

class Solution {
public:
	int findRadius(vector<int>& houses, vector<int>& heaters) {
		sort(houses.begin(), houses.end());
		sort(heaters.begin(), heaters.end());

		int res = 0;
		int j = 0;
		for (int i = 0; i < houses.size(); i++) {
			int dist = numeric_limits<int>::max();
			for (; j < heaters.size(); j++) {
				int nextDist = abs(houses[i] - heaters[j]);

				if (dist < nextDist) {
					break;
				}

				dist = nextDist;
			}
			if (j > 0) j--;
			res = max(res, dist);
		}

		return res;
	}
};

풀이 후기

오랜만에 포스팅을 한다. 그동안에 안풀었던 것은 아닌데.. 일에 치이다 보니 소홀했던것을 사실이다. 오래 했는데도 습관화란 참 힘든 것 같다. 이런 어려운 문제를 만나면 더더욱이나😑

profile
개발자 성장일기

0개의 댓글