comments | difficulty | edit_url |
---|---|---|
true |
中等 |
在一个数组 nums
中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。
示例 1:
输入:nums = [3,4,3,3] 输出:4
示例 2:
输入:nums = [9,1,7,9,7,9,7] 输出:1
限制:
1 <= nums.length <= 10000
1 <= nums[i] < 2^31
我们用一个长度为 32 的数组
时间复杂度
class Solution:
def singleNumber(self, nums: List[int]) -> int:
cnt = [0] * 32
for x in nums:
for i in range(32):
cnt[i] += x & 1
x >>= 1
return sum(1 << i for i in range(32) if cnt[i] % 3)
class Solution {
public int singleNumber(int[] nums) {
int[] cnt = new int[32];
for (int x : nums) {
for (int i = 0; i < 32; ++i) {
cnt[i] += x & 1;
x >>= 1;
}
}
int ans = 0;
for (int i = 0; i < 32; ++i) {
if (cnt[i] % 3 == 1) {
ans |= 1 << i;
}
}
return ans;
}
}
class Solution {
public:
int singleNumber(vector<int>& nums) {
int cnt[32]{};
for (int& x : nums) {
for (int i = 0; i < 32; ++i) {
cnt[i] += x & 1;
x >>= 1;
}
}
int ans = 0;
for (int i = 0; i < 32; ++i) {
if (cnt[i] % 3) {
ans |= 1 << i;
}
}
return ans;
}
};
func singleNumber(nums []int) (ans int) {
cnt := [32]int{}
for _, x := range nums {
for i := range cnt {
cnt[i] += x & 1
x >>= 1
}
}
for i, v := range cnt {
if v%3 == 1 {
ans |= 1 << i
}
}
return
}
impl Solution {
pub fn single_number(nums: Vec<i32>) -> i32 {
let mut counts = [0; 32];
for num in nums.iter() {
for i in 0..32 {
counts[i] += (num >> i) & 1;
}
}
let mut res = 0;
for count in counts.iter().rev() {
res <<= 1;
res |= count % 3;
}
res
}
}
/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function (nums) {
const cnt = new Array(32).fill(0);
for (let x of nums) {
for (let i = 0; i < 32; ++i) {
cnt[i] += x & 1;
x >>= 1;
}
}
let ans = 0;
for (let i = 0; i < 32; ++i) {
if (cnt[i] % 3) {
ans |= 1 << i;
}
}
return ans;
};
public class Solution {
public int SingleNumber(int[] nums) {
int[] cnt = new int[32];
foreach(int x in nums) {
int v = x;
for (int i = 0; i < 32; ++i) {
cnt[i] += v & 1;
v >>= 1;
}
}
int ans = 0;
for (int i = 0; i < 32; ++i) {
if (cnt[i] % 3 == 1) {
ans |= 1 << i;
}
}
return ans;
}
}
class Solution {
func singleNumber(_ nums: [Int]) -> Int {
var bitCounts = [Int](repeating: 0, count: 32)
for num in nums {
var x = num
for i in 0..<32 {
bitCounts[i] += x & 1
x >>= 1
}
}
var result = 0
for i in 0..<32 {
if bitCounts[i] % 3 == 1 {
result |= 1 << i
}
}
return result
}
}