代码拉取完成,页面将自动刷新
/**
* Question Link: https://leetcode.com/problems/single-number-ii/
* Primary idea: Every number has 64 bits, for the i-th bit of each number.
* In total, we should have (nums.count) 0s and 1s.
* If the i-th bit of the single number is 1, then we should have (3n + 1) 1s, and (3n) 0s.
* Otherwise, the i-th bit is 0.
* In this way, we can calculate each bit of the single number.
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class SingleNumberII {
func singleNumber(nums: [Int]) -> Int {
var ans = 0
var sum = 0
for i in 0..<64 {
sum = 0
let tmp = (1 << i)
for j in 0..<nums.count {
if tmp & nums[j] != 0 {
sum = sum + 1
}
}
if sum % 3 == 1 {
ans = ans ^ tmp
}
}
return ans
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。