首页 技术 正文
技术 2022年11月21日
0 收藏 497 点赞 4,925 浏览 1480 个字

For a web developer, it is very important to know how to design a web page’s size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:

1. The area of the rectangular web page you designed must equal to the given target area.

2. The width W should not be larger than the length L, which means L >= W.

3. The difference between length L and width W should be as small as possible.

You need to output the length L and the width W of the web page you designed in sequence.

Example:

Input: 4
Output: [2, 2]
Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.

Note:

    1. The given area won’t exceed 10,000,000 and is a positive integer
    2. The web page’s width and length you designed must be positive integers.

这道题让我们根据面积来求出矩形的长和宽,要求长和宽的差距尽量的小,那么就是说越接近正方形越好。那么我们肯定是先来判断一下是不是正方行,对面积开方,如果得到的不是整数,说明不是正方形。那么我们取最近的一个整数,看此时能不能整除,如果不行,就自减1,再看能否整除。最坏的情况就是面积是质数,最后减到了1,那么返回结果即可,参见代码如下:

解法一:

class Solution {
public:
vector<int> constructRectangle(int area) {
int r = sqrt(area);
while (area % r != ) --r;
return {area / r, r};
}
};

如果我们不想用开方运算sqrt的话,那就从1开始,看能不能整除,循环的终止条件是看平方值是否小于等于面积,参见代码如下:

解法二:

class Solution {
public:
vector<int> constructRectangle(int area) {
int r = ;
for (int i = ; i * i <= area; ++i) {
if (area % i == ) r = i;
}
return {area / r, r};
}
};

参考资料:

https://discuss.leetcode.com/topic/76469/3ms-concise-c

https://discuss.leetcode.com/topic/76314/3-line-clean-and-easy-understand-solution

LeetCode All in One 题目讲解汇总(持续更新中…)

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,038
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,524
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,372
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,152
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,785
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,868