在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a blacklist Optimize it such that it minimizes the call to system’s Note:
Example 1: Input:
[[1,[]],[],[],[]]
Output: [null,0,0,0]
Example 2: Input:
[[2,[]],[],[],[]]
Output: [null,1,1,1]
Example 3: Input:
[[3,[1]],[],[],[]]
Output: [null,0,0,2]
Example 4: Input:
[[4,[2]],[],[],[]]
Output: [null,1,3,1]
Explanation of Input Syntax: The input is two lists: the subroutines called and their arguments. 给定一个包含 [0,n ) 中独特的整数的黑名单 B,写一个函数从 [ 0,n ) 中返回一个不在 B 中的随机整数。 对它进行优化使其尽量少调用系统方法 提示:
示例 1: 输入: ["Solution","pick","pick","pick"] [[1,[]],[],[],[]] 输出: [null,0,0,0] 示例 2: 输入: ["Solution","pick","pick","pick"] [[2,[]],[],[],[]] 输出: [null,1,1,1] 示例 3: 输入: ["Solution","pick","pick","pick"] [[3,[1]],[],[],[]] Output: [null,0,0,2] 示例 4: 输入: ["Solution","pick","pick","pick"] [[4,[2]],[],[],[]] 输出: [null,1,3,1] 输入语法说明: 输入是两个列表:调用成员函数名和调用的参数。 Runtime: 984 ms
Memory Usage: 23.4 MB
1 class Solution { 2 var M:Int = 0 3 var map:[Int:Int] = [Int:Int]() 4 init(_ N: Int, _ blacklist: [Int]) { 5 var N = N 6 for b in blacklist 7 { 8 map[b] = -1 9 } 10 M = N - map.count 11 for b in blacklist 12 { 13 if b < M 14 { 15 while (map[N - 1] != nil) 16 { 17 N -= 1 18 } 19 map[b] = N - 1 20 N -= 1 21 } 22 } 23 } 24 25 func pick() -> Int { 26 var p:Int = Int.random(in:0..<M) 27 return map[p] == nil ? p : map[p]! 28 } 29 } 30 31 /** 32 * Your Solution object will be instantiated and called as such: 33 * let obj = Solution(N, blacklist) 34 * let ret_1: Int = obj.pick() 35 */ 1628ms 1 class Solution { 2 3 init(_ N: Int, _ blacklist: [Int]) { 4 M = N - blacklist.count 5 for n in blacklist { 6 mapping[n] = 0 7 } 8 9 var i = M 10 for n in blacklist { 11 if n < M { 12 while mapping[i] != nil { 13 i += 1 14 } 15 mapping[n] = i 16 i += 1 17 } 18 } 19 } 20 21 func pick() -> Int { 22 let r = Int.random(in: 0..<M) 23 if let n = mapping[r] { 24 return n 25 } 26 return r 27 } 28 29 var M : Int 30 var mapping = [Int: Int]() 31 } 32 33 /** 34 * Your Solution object will be instantiated and called as such: 35 * let obj = Solution(N, blacklist) 36 * let ret_1: Int = obj.pick() 37 */
|
请发表评论