137.只出现一次的数字II
链接:137.只出现一次的数字II
难度:Medium
标签:位运算、数组
简介:给你一个整数数组 nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。
题解 1 - python
- 编辑时间:2023-10-15
- 执行用时:92ms
- 内存消耗:17.8MB
- 编程语言:python
- 解法介绍:统计每一个位置上1的个数。
import ctypes
    class Solution:
        def singleNumber(self, nums: List[int]) -> int:
            return ctypes.c_int32(reduce(
                lambda res, i: res | (1 if sum((num >> i) & 1 for num in nums) % 3 != 0 else 0) << i, 
                [i for i in range(0, 32)],
                0
            )).value
题解 2 - typescript
- 编辑时间:2021-04-30
- 执行用时:76ms
- 内存消耗:40.4MB
- 编程语言:typescript
- 解法介绍:利用 map 储存。
function singleNumber(nums: number[]): number {
  return [
    ...nums
      .reduce((map, v) => {
        map.set(v, (map.get(v) ?? 0) + 1);
        return map;
      }, new Map<number, number>())
      .entries(),
  ].filter(([, v]) => v === 1)[0][0];
}
题解 3 - typescript
- 编辑时间:2021-04-30
- 执行用时:96ms
- 内存消耗:40.1MB
- 编程语言:typescript
- 解法介绍:排序后判断数量。
function singleNumber(nums: number[]): number {
  const len = nums.length;
  nums.sort((a, b) => a - b);
  let i = 0;
  while (i < len - 1) {
    if (nums[i] === nums[i + 1]) i += 3;
    else break;
  }
  return nums[i];
}