leetcode剑指Offer 56-II. 数组中数字出现的次数II Java

做题博客链接

https://blog.csdn.net/qq_43349112/article/details/108542248

题目链接

https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof/

描述

在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。

限制:

1 <= nums.length <= 10000
1 <= nums[i] < 2^31

示例

示例 1:

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

示例 2:

输入:nums = [9,1,7,9,7,9,7]
输出:1

初始代码模板

class Solution {
    
    
    public int singleNumber(int[] nums) {
    
    
       
    }
}

代码

推荐题解:
https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof/solution/javashi-xian-jian-zhi-si-lu-wei-yun-suan-zhu-wei-t/

class Solution {
    
    
    public int singleNumber(int[] nums) {
    
    
        int[] bit = new int[32];
        int num = 1;
        for (int i = 0; i < 32; i++) {
    
    
            for (int n : nums) {
    
    
                if ((num & n) != 0) {
    
    
                    bit[i]++;
                }
            }
            num <<= 1;
        }

        int res = 0;
        for (int i = 31; i >= 0; i--) {
    
    
            res <<= 1;
            res += bit[i] % 3;
        }

        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43349112/article/details/113811517