0位运算中等 leetcode137. 只出现一次的数字 II

137. 只出现一次的数字 II

题目描述

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

位运算解法

int一共32位,遍历数组统计数组元素在32位的每一位上1出现的次数。
因为只有一个元素只出现一次,其余每个元素均出现了三次。所以一个位的1累计次数是3N时表示,唯一元素在该位上是0。位的1累计次数是3N+1表示唯一元素在该位上是1。

class Solution {
    public int singleNumber(int[] nums) {
        int res = 0;//保存唯一元素
        int sign;//只在一个位是1,其余位是0。1从第1位一直移动到32位
        for(int i = 0; i < 32; i++){
            int amount = 0;//统计在某一位上1累计的次数
            sign = 1 << i; 
            for(int j = 0; j < nums.length; j++){
                if((nums[j] & sign) != 0){
                    amount++;
                }
            }
            if(amount % 3 == 1){//为真说明唯一元素在该位上是1
                res = res | sign;
            }
        }
        return res;
    }
}
HashMap解法

遍历数组将元素和其出现的次数作为键值对保存在map中,再次遍历数组找到次数是1的键值对,返回Key。

class Solution {
    public int singleNumber(int[] nums) {
        HashMap<Integer,Integer> map =new HashMap<>();
        int res = 0;
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(nums[i])){
                int temp = map.get(nums[i]);
                map.put(nums[i],temp+1);
            }else{
                map.put(nums[i],1);
            }
        }
        for(int i = 0; i < nums.length; i++){
            if(map.get(nums[i]) == 1){
                res = nums[i];
            }
        }
        return res;
    }
}

你可能感兴趣的:(算法,leetcode)