未分類

Construct the Rectangle

Construct the Rectangle

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:

1
2
3
4
5
1. The area of the rectangular web page you designed must equal to the given target area.
2. The width W should not be larger than the length L, which means L >= W.
3. 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.

For Example:

1
2
3
4
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.

Note:

  1. The given area won’t exceed 10,000,000 and is a positive integer
  2. The web page’s width and length you designed must be positive integers.

Default:

1
2
3
func constructRectangle(area int) []int {
}

解答思路:

大致就是做因式分解,找出兩因數差距為最小值,所以如果我們將給予的值從1開始整除,原則上因數間的差距會慢慢變小,而當差距到最小時,下一個差距反而變大的話(或是相減的差距變為負數),此時前一組就是我們要找的目標,在最後要放的時候記得要將因數較大的放第一個(長度L),小的擺在第二個(寬度W),因為結果要的是L, W

程式碼解說:

一開始先初始化一陣列但長度僅只有2用於存放結果,之後利用回圈將面積從1開始與常數做整除,如果面積與常數相除能完全整除,且商數(比較大)與常數相減大於0,就將商數放入結果陣列的第一個(長度),至於常數則是放第二個(寬度),一直到發現商數減去常數時為負,表示常數(寬度)已經比商數(長度)大,此時便跳離回圈將前一組因數結果做回傳

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var tmp int
result := make([]int, 2)
for i := 1; i <= area; i++ {
if area%i == 0 {
tmp = area / i
if tmp-i >= 0 {
result[0] = tmp
result[1] = i
} else {
break
}
}
}
return result

完整程式碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func constructRectangle(area int) []int {
var tmp int
result := make([]int, 2)
for i := 1; i <= area; i++ {
if area%i == 0 {
tmp = area / i
if tmp-i >= 0 {
result[0] = tmp
result[1] = i
} else {
break
}
}
}
return result
}

總結:

給予一長方形的面積,找出長與寬且兩者差距需為最小值,將給予的面積從1開始整除,因數間的差距會慢慢變小,當差距到最小時,下一個差距反而變大的話(或是相減的差距變為負數),此時前一組因數就是我們要找的目標。

分享到