博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 475. Heaters
阅读量:5950 次
发布时间:2019-06-19

本文共 2407 字,大约阅读时间需要 8 分钟。

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: 5Output: 2Explanation: 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: 1Output: 0Explanation: 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

转载地址:http://tlsxx.baihongyu.com/

你可能感兴趣的文章
用java数组模拟登录和注册功能
查看>>
关于jsb中js与c++的相互调用
查看>>
UVA 122 Trees on the level 二叉树 广搜
查看>>
POJ-2251 Dungeon Master
查看>>
tortoisesvn的安装
查看>>
URAL 1353 Milliard Vasya's Function DP
查看>>
速读《构建之法:现代软件工程》提问
查看>>
Android onclicklistener中使用外部类变量时为什么需要final修饰【转】
查看>>
django中聚合aggregate和annotate GROUP BY的使用方法
查看>>
TFS简介
查看>>
docker管理平台 shipyard安装
查看>>
Bootstrap3 栅格系统-简介
查看>>
ADODB类库操作查询数据表
查看>>
博客搬家了
查看>>
Python中使用ElementTree解析xml
查看>>
sed处理文本
查看>>
jquery 操作iframe、frameset
查看>>
解决vim中不能使用小键盘
查看>>
jenkins权限管理,实现不同用户组显示对应视图views中不同的jobs
查看>>
我的友情链接
查看>>