Skip to content

Latest commit

 

History

History
49 lines (40 loc) · 1.21 KB

README_CN.md

File metadata and controls

49 lines (40 loc) · 1.21 KB

137. 只出现一次的数字 II

给你一个整数数组 nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。

你必须设计并实现线性时间复杂度的算法且使用常数级空间来解决此问题。

示例 1:

输入: nums = [2,2,3,2]
输出: 3

示例 2:

输入: nums = [0,1,0,1,0,1,99]
输出: 99

提示:

  • 1 <= nums.length <= 3 * 104
  • -231 <= nums[i] <= 231 - 1
  • nums 中,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次

题解 (Rust)

1. 题解

impl Solution {
    pub fn single_number(nums: Vec<i32>) -> i32 {
        let mut bitcount = [0; 32];
        let mut ret = 0;

        for num in &nums {
            for i in 0..32 {
                if (num >> i) & 1 == 1 {
                    bitcount[i] += 1;
                }
            }
        }

        for i in 0..32 {
            if bitcount[i] % 3 == 1 {
                ret |= 1 << i;
            }
        }

        ret
    }
}