Header Ad

Leetcode Construct the Rectangle problem solution

In this Leetcode Construct the Rectangle problem solution A web developer needs 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.

Return an array [L, W] where L and W are the length and width of the web page you designed in sequence.

Leetcode Construct the Rectangle problem solution


Problem solution in Python.

class Solution:
    def constructRectangle(self, area: int) -> List[int]:
        from functools import reduce

        def factors(n):    
            return list(set(reduce(list.__add__, 
                        ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
        
        l1 = factors(area)
        l2 = []
        max_diff = area - 1
        for i in l1:
            
            a = area//i
            if i >= a and i - a < max_diff:
                max_diff = i - a
                l2.append([i])
        if not l2:
            return [area, 1]
        else:  
            b = min(l2)[0]
            return [b, area//b]

Problem solution in Java.

class Solution {
    public int[] constructRectangle(int area) {
        int sqrt = (int)Math.sqrt(area);
        for(int i = sqrt; i > 0; i--){
            if(area % i == 0)
                return new int[]{area/i, i};
        }
        return new int[]{area, 1};
    }
}


Problem solution in C++.

vector<int> constructRectangle(int area) {
        for(int mid = sqrt(area); mid>0; mid--)
            if (!(area%mid))
                return {area/mid, mid};
}


Post a Comment

1 Comments

  1. 1xbet korean: What Is 1xbet Korean? | LegalBet
    1xbet korean is worrione a Sportsbook that was founded in 2018 and has 바카라사이트 a strong online sportsbook, as well as poker, live casino, and 1xbet korean sports betting products.

    ReplyDelete