在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n). There are n + 1 taps located at points [0, 1, ..., n] in the garden. Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open. Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.
Example 1:
Input: n = 3, ranges = [0,0,0,0] Input: n = 7, ranges = [1,2,1,0,2,1,0,1] Input: n = 8, ranges = [4,0,0,0,0,0,0,0,4] Input: n = 8, ranges = [4,0,0,0,4,0,0,0,4] Constraints: 1 <= n <= 10^4 在 x 轴上有一个一维的花园。花园长度为 n,从点 0 开始,到点 n 结束。 花园里总共有 n + 1 个水龙头,分别位于 [0, 1, ..., n] 。 给你一个整数 n 和一个长度为 n + 1 的整数数组 ranges ,其中 ranges[i] (下标从 0 开始)表示:如果打开点 i 处的水龙头,可以灌溉的区域为 [i - ranges[i], i + ranges[i]] 。 请你返回可以灌溉整个花园的 最少水龙头数目 。如果花园始终存在无法灌溉到的地方,请你返回 -1 。
示例 1:
输入:n = 5, ranges = [3,4,1,1,0,0] 输入:n = 3, ranges = [0,0,0,0] 输入:n = 7, ranges = [1,2,1,0,2,1,0,1] 输入:n = 8, ranges = [4,0,0,0,0,0,0,0,4] 输入:n = 8, ranges = [4,0,0,0,4,0,0,0,4] 提示: 1 <= n <= 10^4 Runtime: 148 ms
Memory Usage: 21.7 MB
1 class Solution { 2 func minTaps(_ n: Int, _ ranges: [Int]) -> Int { 3 var rg:[[Int]] = [[Int]](repeating: [Int](repeating: 0, count: 2), count: n + 1) 4 for i in 0...n 5 { 6 let s:Int = i - ranges[i] 7 let e:Int = i + ranges[i] 8 rg[i] = [s < 0 ? 0 : s, e < n ? e : n] 9 } 10 rg = rg.sorted(by:{ 11 if $0[0] == $1[0] 12 { 13 return $0[1] < $1[1] 14 } 15 else 16 { 17 return $0[0] < $1[0] 18 } 19 } 20 ) 21 var ans:Int = 0 22 var i:Int = 0 23 var start:Int = 0 24 var end:Int = 0 25 while(start < n && i <= n) 26 { 27 while(i <= n && rg[i][0] <= start) 28 { 29 end = max(end, rg[i][1]) 30 i += 1 31 } 32 if end <= start{return -1} 33 start = end 34 ans += 1 35 } 36 return ans 37 } 38 }
|
请发表评论