天天看点

剑指Offer打卡day42——ACWing 74. 数组中唯一只出现一次的数字

【题目描述】

剑指Offer打卡day42——ACWing 74. 数组中唯一只出现一次的数字

ACWing 74. 数组中唯一只出现一次的数字

【思路】

使用Map来统计每个数字出现的次数

时间复杂度O(n)

空间复杂度O(n)

class Solution {
    public int findNumberAppearingOnce(int[] nums) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int x: nums){
            if( map.containsKey(x) ) map.put( x, map.get(x) + 1);
            else map.put(x, 1);
        }
        for(int x: nums)
            if( map.get(x) == 1 )
                return x;
        return 0;
    }
}
           

如果要求只使用 O(n) 的时间和额外 O(1) 的空间,该怎么做呢?

【思路】

统计每一位1的个数 若不能被3整除 则说明要求的数字该位为1

class Solution {
    public int findNumberAppearingOnce(int[] nums) {
        
        int ans = 0;
        for(int i = 31; i >= 0; i --){
            int cnt = 0;
            for(int x: nums){
                if( ( x >> i & 1 )== 1){
                    cnt ++;
                }
            }
            if( cnt % 3 == 1) ans = ans *2 +1; //该位为1
            else ans *= 2;
        }
        
        return ans;
    }
}
           

继续阅读