剑指Offer-59数组中数字出现的次数 II

public int singleNumber(int[] nums) {
    HashMap<Integer, Boolean> hashMap = new HashMap<>();
    // 遍历将出现一次的数字value置为true,出现多次的value置为false
    for (int num : nums){
        if (hashMap.get(num) == null){
            hashMap.put(num, true);
        }else {
            hashMap.put(num, false);
        }
    }
    int res = -1;
    // 找到value为true的数字
    for(int key: hashMap.keySet()){
        if (hashMap.get(key)){
            res = key;
            break;
        }
    }
    return res;
}

我用的笨方法 来看看大神是怎么解的

public int singleNumber(int[] nums) {
    int ones = 0, twos = 0;
    for(int num : nums){
        ones = ones ^ num & ~twos;
        twos = twos ^ num & ~ones;
    }
    return ones;
}

猜你喜欢

转载自blog.csdn.net/a792396951/article/details/114286118
今日推荐