在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an array Return a list of booleans Example 1: Input: [0,1,1]
Output: [true,false,false]
Explanation:
The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. Only the first number is divisible by 5, so answer[0] is true.
Example 2: Input: [1,1,1]
Output: [false,false,false]
Example 3: Input: [0,1,1,1,1,1]
Output: [true,false,false,false,true,false]
Example 4: Input: [1,1,1,0,1]
Output: [false,false,false,false,false]
Note:
给定由若干 返回布尔值列表 示例 1: 输入:[0,1,1] 输出:[true,false,false] 解释: 输入数字为 0, 01, 011;也就是十进制中的 0, 1, 3 。只有第一个数可以被 5 整除,因此 answer[0] 为真。 示例 2: 输入:[1,1,1] 输出:[false,false,false] 示例 3: 输入:[0,1,1,1,1,1] 输出:[true,false,false,false,true,false] 示例 4: 输入:[1,1,1,0,1] 输出:[false,false,false,false,false] 提示:
Runtime: 88 ms
Memory Usage: 20.7 MB
1 class Solution { 2 func prefixesDivBy5(_ A: [Int]) -> [Bool] { 3 var ret:[Bool] = [Bool]() 4 var x:Int = 0 5 for v in A 6 { 7 x = (x * 2 + v) % 5 8 ret.append(x == 0) 9 } 10 return ret 11 } 12 } 88ms 1 class Solution { 2 func prefixesDivBy5(_ A: [Int]) -> [Bool] { 3 var curr = 0 4 var result = A.map { _ in false } 5 for i in 0..<A.count { 6 curr = (curr << 1) + A[i] 7 result[i] = (curr % 5 == 0) 8 curr = curr % 5 9 } 10 return result 11 } 12 } 96ms 1 class Solution { 2 func prefixesDivBy5(_ A: [Int]) -> [Bool] { 3 var sum = 0 4 var ost = Array([1,2,4,3].reversed()) 5 let shift = A.count % 4 6 var res: [Bool] = [] 7 for (i,n) in A.enumerated() { 8 let ind = ((i+shift) % 4) 9 sum += (n == 1 ? ost[ind] : 0) 10 res.append((sum % 5) == 0) 11 } 12 13 return res 14 } 15 } 104ms 1 class Solution { 2 func prefixesDivBy5(_ A: [Int]) -> [Bool] { 3 var num = 0 4 var answers = [Bool]() 5 for a in A { 6 num += a 7 answers.append(num % 5 == 0) 8 num *= 2 9 num = num % 5 10 } 11 12 return answers 13 } 14 }
|
请发表评论