Sword refers to the number of times the number appears in the Offer-59 array 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;
}

I used the dumb way to see how the great god solved it

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

Guess you like

Origin blog.csdn.net/a792396951/article/details/114286118