资讯专栏INFORMATION COLUMN

[LeetCode/LintCode] Construct the Rectangle

sf_wangchong / 688人阅读

Problem

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:

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

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

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.

Solution
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) {
        int squareRoot = (int) Math.sqrt(area);
        int w = squareRoot;
        while (area%w != 0) {
           w--;
        }
        return new int[] {area/w, w};
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69550.html

相关文章

  • [LeetCode/LintCode] Top K Frequent Words

    LeetCode version Problem Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, t...

    0x584a 评论0 收藏0
  • [LeetCode/LintCode] First Bad Version

    摘要:分析最后一次循环的时刻当与相差小于时,总是那么如果是,下一次直接跳出循环,返回当与相差大于时,是,变成,如果是,循环结束的条件将是循环结束,返回 Problem The code base version is an integer start from 1 to n. One day, someone committed a bad version in the code case,...

    lowett 评论0 收藏0
  • [LeetCode/LintCode] Largest Palindrome Product

    Problem Find the largest palindrome made from the product of two n-digit numbers. Since the result could be very large, you should return the largest palindrome mod 1337. Example Input: 2Output: 987Ex...

    Barry_Ng 评论0 收藏0
  • [LeetCode/LintCode] Remove Nth Node From End of L

    Problem Given a linked list, remove the nth node from the end of list and return its head. Example Given linked list: 1->2->3->4->5->null, and n = 2. After removing the second node from the end, the l...

    Jaden 评论0 收藏0
  • [LeetCode/LintCode] Happy Number

    Problem Write an algorithm to determine if a number is happy.A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squar...

    崔晓明 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<