leetcode 475. Heaters

Description

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:
The given integer is guaranteed to fit within the range of a 32-bit signed integer.
You could assume no leading zero bit in the integer’s binary representation.

Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

Discuss Solution

class Solution {
public:
    int findRadius(vector& houses, vector& heaters) {
        if (heaters.size() == 0) {
            return 0;
        }
        sort(houses.begin(), houses.end());
        sort(heaters.begin(), heaters.end());
        int radius = 0;
        int index = 0;
        for (int i = 0; i < houses.size(); i++) {
            while (index + 1 < heaters.size() && (abs(heaters[index+1] - houses[i]) <= abs(heaters[index] - houses[i]))) {
                index++;
            }
            radius = max(radius, abs(heaters[index] - houses[i]));
        }
        return radius;
    }
};

自己仿照的写了一下, 提交后error, 唯一的区别就是下面code中注释的部分"<"和"<="的区别.
改代码作者做出解释:

  • In your while loop line, why it has to be "<=", "<" will be wrong.

The problem is with duplicates, when multiple heaters are at the same position, then we want to proceed as far as possible, otherwise heater's index would be blocked.

For example, houses = [1,2] and heaters = [1,1,2]
then the radius is 0, but if change <= to <, then the second 1 would block later 2 for heater positions so it would get wrong result of radius 1

class Solution {
public:
    int findRadius(vector &houses, vector &heaters) {
        sort(houses.begin(), houses.end());
        sort(heaters.begin(), heaters.end());
        int r = 0, j = 0;
        for (int i = 0; i < houses.size(); ++i) {
//            while (j + 1 < heaters.size() && abs(heaters[j + 1] - houses[i]) < abs(heaters[j] - houses[i])) ++j;
            // "<"改为"<="才正确. 原因是houses=[1,2], heaters=[1,1,2], 如果采用"<"会导致错误结果
            while (j + 1 < heaters.size() && abs(heaters[j + 1] - houses[i]) <= abs(heaters[j] - houses[i])) ++j;
            r = max(abs(heaters[j] - houses[i]), r);
        }
        return r;
    }
};

Reference

  • leetcode 475. Heaters

你可能感兴趣的:(算法,leetcode,c++)