在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ On the first row, we write a Given row Examples: Input: N = 1, K = 1 Output: 0 Input: N = 2, K = 1 Output: 0 Input: N = 2, K = 2 Output: 1 Input: N = 4, K = 5 Output: 1 Explanation: row 1: 0 row 2: 01 row 3: 0110 row 4: 01101001 Note:
在第一行我们写上一个 给定行数 例子: 输入: N = 1, K = 1 输出: 0 输入: N = 2, K = 1 输出: 0 输入: N = 2, K = 2 输出: 1 输入: N = 4, K = 5 输出: 1 解释: 第一行: 0 第二行: 01 第三行: 0110 第四行: 01101001 注意:
Runtime: 4 ms
Memory Usage: 18.4 MB
1 class Solution { 2 func kthGrammar(_ N: Int, _ K: Int) -> Int { 3 if N == 1{ 4 return 0 5 } 6 7 return K % 2 == 0 ? (kthGrammar(N-1,K/2) == 0 ? 1 : 0 ):(kthGrammar(N-1,(K+1)/2) == 1 ? 1 : 0) 8 } 9 } Runtime: 4 ms
Memory Usage: 18.4 MB
1 class Solution { 2 func kthGrammar(_ N: Int, _ K: Int) -> Int { 3 var K = K 4 var res:Int = 0 5 while (K > 1) 6 { 7 K = (K % 2 == 1) ? K + 1 : K / 2 8 res ^= 1 9 } 10 return res 11 } 12 } 4ms 1 class Solution { 2 func kthGrammar(_ N: Int, _ K: Int) -> Int { 3 var s = pow(Double(2), Double(N - 1)) 4 var flips = 0 5 var K = K 6 while (s > 2){ 7 if K > Int(s / 2) { 8 K -= Int(s / 2) 9 flips += 1 10 } 11 s /= 2 12 } 13 K -= 1 // K is either 2 or 1 14 if flips % 2 == 1 { 15 K = 1 - K 16 } 17 return K 18 } 19 } 8ms 1 class Solution { 2 func kthGrammar(_ N: Int, _ K: Int) -> Int { 3 if K == 1 { 4 return 0 5 } 6 let halfCount = Int(pow(2.0, Double(N-2))) 7 let rm = K%halfCount 8 if K <= halfCount { 9 return kthGrammar(N-1, rm == 0 ? halfCount : rm) 10 } else { 11 return kthGrammar(N-1, rm == 0 ? halfCount : rm) == 0 ? 1 : 0 12 } 13 } 14 }
|
请发表评论