矩形编码的最小周长

时间:2014-09-02 10:17:26

标签: java algorithm

这是我对编纂任务MInPerimeterRectangle的解决方案。它工作正常,但如果我们有一个测试用例:“982451653”编译器获得TIMEOUT ERROR。这是因为这个矩形的最小周长是由边A = 1和B = 982451653创建的。

所以我有一个问题。是否有可能更快地使解决方案?

class Solution {
        public int solution(int N) {

            int A = 0;
            int B = N;
            int perimeter = 0;
            for (A = 1; A <= B; A++) {
                if (A * B == N){
                    perimeter = 2 * (A + B);
                    System.out.println("perimeter: " + perimeter);
                }
                if (N % (A+1) == 0) 
                    B = N/(A+1);
            }
            System.out.println("A: " + A);

            return perimeter;
        }

    }

修改

这是任务:

An integer N is given, representing the area of some rectangle.

The area of a rectangle whose sides are of length A and B is A * B, and the perimeter is 2 * (A + B).

The goal is to find the minimal perimeter of any rectangle whose area equals N. The sides of this rectangle should be only integers.

For example, given integer N = 30, rectangles of area 30 are:

        (1, 30), with a perimeter of 62,
        (2, 15), with a perimeter of 34,
        (3, 10), with a perimeter of 26,
        (5, 6), with a perimeter of 22.

Write a function:

    int solution(int N); 

that, given an integer N, returns the minimal perimeter of any rectangle whose area is exactly equal to N.

For example, given an integer N = 30, the function should return 22, as explained above.

Assume that:

        N is an integer within the range [1..1,000,000,000].

Complexity:

        expected worst-case time complexity is O(sqrt(N));
        expected worst-case space complexity is O(1).

2 个答案:

答案 0 :(得分:4)

设l1和l2为边长。最小化|l1-l2|的Concider将最小化周长。所以这将是一个解决方案:

public int solution(int n) {
    int sumMin =Integer.MAX_VALUE;
    for(int i=1 ;i<=Math.sqrt(n);i++) {
        if(n%i==0 ) {
            if(2*(i+n/i) < sumMin) sumMin=2*(i+n/i);    
        }   
    }   
    return sumMin;
}

答案 1 :(得分:0)

我不确定你更快地使用这个解决方案是什么意思。任何改变它的东西都会使它不再是这个解决方案。

你的根本问题是你满溢。请改用long

您的下一个问题是,您正在查看过多的A值。在找到N的第一个因子大于sqrt(N)之前,您的循环才会退出。但如果N为素数,则表示您的算法为O(N)。我建议重新考虑你的方法。微积分告诉我们最小周长是一个正方形,因此这意味着您希望N因子最接近sqrt(N)。因此,您希望找到一种有效的方法来生成N的因子,并从那里开始。