在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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. The area of the rectangular web page you designed must equal to the given target area. 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. Note:
作为一位web开发者, 懂得怎样去规划一个页面的尺寸是很重要的。 现给定一个具体的矩形页面面积,你的任务是设计一个长度为 L 和宽度为 W 且满足以下要求的矩形的页面。要求: 1. 你设计的矩形页面必须等于给定的目标面积。 2. 宽度 W 不应大于长度 L,换言之,要求 L >= W 。 3. 长度 L 和宽度 W 之间的差距应当尽可能小。 你需要按顺序输出你设计的页面的长度 L 和宽度 W。 示例: 输入: 4 输出: [2, 2] 解释: 目标面积是 4, 所有可能的构造方案有 [1,4], [2,2], [4,1]。 但是根据要求2,[1,4] 不符合要求; 根据要求3,[2,2] 比 [4,1] 更能符合要求. 所以输出长度 L 为 2, 宽度 W 为 2。 说明:
8ms 1 class Solution { 2 func constructRectangle(_ area: Int) -> [Int] { 3 var w = Int(sqrt(Double(area))) 4 while area % w != 0 { 5 w -= 1 6 } 7 return [area / w, w] 8 } 9 } 8ms 1 class Solution { 2 func constructRectangle(_ area: Int) -> [Int] { 3 var minDiff = Int.max 4 var minDiffWidth: Int? 5 let maxWidth = Int(ceil(sqrt(Double(area)))) 6 7 for width in 1 ... maxWidth { 8 guard area % width == 0 else { continue } 9 10 let length = area / width 11 if length >= width, length - width < minDiff { 12 minDiff = length - width 13 minDiffWidth = width 14 } 15 } 16 if let minDiffWidth = minDiffWidth { 17 return [area / minDiffWidth, minDiffWidth] 18 } else { 19 return [area, 1] 20 } 21 } 22 } 12ms 1 class Solution { 2 func constructRectangle(_ area: Int) -> [Int] { 3 let maxW = Int(sqrt(Double(area))) 4 var result = [area,1] 5 if maxW >= 2 { 6 for i in 2...maxW { 7 if area % i == 0 { 8 result = [area / i,i] 9 } 10 } 11 } 12 return result 13 } 14 } 12ms 1 class Solution { 2 func constructRectangle(_ area: Int) -> [Int] { 3 var n = Int(sqrt(Double(area))) 4 while area % n != 0 { 5 n -= 1 6 } 7 return [max(n, area/n), min(n, area/n)] 8 } 9 } 20ms 1 class Solution { 2 func constructRectangle(_ area: Int) -> [Int] { 3 var maxW = Int(sqrt(Double(area))) 4 var result = [area,1] 5 while maxW >= 2 { 6 if area % maxW == 0 { 7 result = [area / maxW,maxW] 8 break 9 } 10 maxW -= 1 11 } 12 return result 13 } 14 } 116ms 1 class Solution { 2 func constructRectangle(_ area: Int) -> [Int] { 3 guard area > 0 else { return [0, 0] } 4 let sqr = sqrt(Double(area)) 5 var i = Int(sqr) 6 var j = Int(sqr) 7 var prod = i*j 8 while prod != area { 9 if prod > area { 10 i -= 1 11 } else if prod < area { 12 j += 1 13 } 14 prod = i*j 15 } 16 return [j, i] 17 18 } 19 }
|
请发表评论