Sort Java solution

  • 0

    The idea is to run through all divisors of the area. To find all divisors it is enough to iterate till square root of the area. num*(area/num)==area. We run from the biggest divisor because in that case difference between L and W will smallest.

    public class Solution {
        public int[] constructRectangle(int area) {
            for (int i=(int)Math.sqrt(area); i>=0; i--) {
                if (area%i!=0) continue;
                int div = area/i
                int val = i*div;
                if (val==area) {
                    return new int[]{Math.max(i,div), Math.min(i, div)};
            return new int[]{0,0};

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.