LeetCode - 492. Construct the Rectangle

链接

492. Construct the Rectangle

题意

给出面积,算出符合以下条件的整数长L和宽W:

  1. 面积 = 长 * 宽
  2. L ≥ W
  3. L和W之差尽可能小

思路

为了满足条件,对面积开根号即可,但L和W为整数。因此先让W为面积开根号向下取整,再逐步自减,直到找到满足条件的L

代码

Java:

public class Solution {
    public int[] constructRectangle(int area) {
        int width = (int) Math.sqrt(area);
        while (area % width != 0) {
            width--;
        }
        int length = area / width;
        int[] ans = new int[2];
        ans[0] = length;
        ans[1] = width;
        return ans;
    }
}

效率

Your runtime beats 46.66 % of java submissions.

posted @ 2017-04-25 22:34  zyoung  阅读(228)  评论(0编辑  收藏  举报