题目地址:
https://www.lintcode.com/problem/construct-the-rectangle/description
给定一个正整数 a a a,要求找到一个数对 ( i , j ) (i,j) (i,j)使得 i j = a , i ≥ j ij=a,i\ge j ij=a,i≥j并且 i − j i-j i−j尽量小。
从 a \sqrt a a开始向 1 1 1找 j j j即可。代码如下:
public class Solution {
/**
* @param area: web page’s area
* @return: the length L and the width W of the web page you designed in sequence
*/
public int[] constructRectangle(int area) {
// Write your code here
for (int i = (int) Math.sqrt(area); i >= 1; i--) {
if (area % i == 0) {
return new int[]{area / i, i};
}
}
return null;
}
}
时间复杂度 O ( a ) O(\sqrt a) O(a),空间 O ( 1 ) O(1) O(1)。