剑指offer第56题

题目描述:

在一个数组 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
 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-ii-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:

class Solution {
    public int singleNumber(int[] nums) {
        if(nums.length==1)
            return nums[0];
        int[] cnts = new int[32];
        int base =1;
        for(int i=0;i<32;i++){
            for(int j=0;j<nums.length;j++){
                if((nums[j]&base)!=0)
                    cnts[i]++;
            }
            base<<=1;
        }
        int res=0;
        base = 1;
        for(int i=0;i<32;i++){
            res += cnts[i]%3*base;
            base<<=1;
        }
        return res;

    }
}

 

效率:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章