在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ An image is represented by a binary matrix with For example, given the following image: [ "0010", "0110", "0100" ] and Return 图像由一个二进制矩阵表示,其中0为白色像素,1为黑色像素。黑色像素连接,即只有一个黑色区域。像素水平和垂直连接。给定一个黑色像素的位置(x, y),返回包围所有黑色像素的最小(轴对齐)矩形的区域。 例如,给出以下图像: [ "0010", "0110", "0100" ] X=0,Y=2, 返回6。 Solution: 1 class Solution { 2 func minArea(_ image:inout [String],_ x:Int,_ y:Int) -> Int { 3 var m:Int = image.count 4 var n:Int = image[0].count 5 var up:Int = binary_search(&image, true, 0, x, 0, n, true) 6 var down:Int = binary_search(&image, true, x + 1, m, 0, n, false) 7 var left:Int = binary_search(&image, false, 0, y, up, down, true) 8 var right:Int = binary_search(&image, false, y + 1, n, up, down, false) 9 return (right - left) * (down - up) 10 } 11 12 // Binary Search 13 func binary_search(_ image:inout [String],_ h:Bool,_ i:Int,_ j:Int,_ low:Int,_ high:Int,_ opt:Bool) -> Int 14 { 15 var i = i 16 var j = j 17 while (i < j) 18 { 19 var k:Int = low 20 var mid:Int = (i + j) / 2 21 while (k < high && (h ? image[mid][k] : image[k][mid]) == "0") 22 { 23 k += 1 24 } 25 if (k < high) == opt{ j = mid } 26 else{ i = mid + 1 } 27 } 28 return i 29 } 30 } 31 32 //String扩展 33 extension String { 34 //subscript函数可以检索数组中的值 35 //直接按照索引方式截取指定索引的字符 36 subscript (_ i: Int) -> Character { 37 //读取字符 38 get {return self[index(startIndex, offsetBy: i)]} 39 } 40 } 点击:Playground测试 1 var sol = Solution() 2 var arr:[String] = ["0010","0110","0100"] 3 var x:Int = 0 4 var y:Int = 2 5 print(sol.minArea(&arr,x,y)) 6 //Print 6
|
请发表评论