首页 > 解决方案 > 通过 Haspmap 求解单个数字,返回始终为“@”

问题描述

这是 leetcode 的一个问题。Leetcode - 单数 I .

我想使用hashmap来解决它,但是我的返回键总是“@”是错误的。

这是代码:

class Solution {
public int singleNumber(int[] nums) {
    char[] y = ("" + nums).toCharArray();
    int size=y.length;

    Map<Character,Integer>map=new HashMap<>();
    int i =0;
    while(i!=size) {
        if(map.containsKey(y[i])==false) {
            map.put(y[i],1);
        }
        else {
            int oldval=map.get(y[i]);
            int newval=oldval+1;
            map.put(y[i],newval);
        }
        ++i;
    }

    Set<Map.Entry<Character,Integer>>hmp=map.entrySet();
    for(Map.Entry<Character,Integer>data:hmp) {
        if(data.getValue()==1){
           return data.getKey();
        }
    }
     return 0;
}
}

我不知道出了什么问题。(也许是 getkey() 部分?)

我出现了你的所有帮助!

标签: javaalgorithmhashmap

解决方案


使用按位异或:

int result = 0;
for (int n : nums) {
  result ^= n;
}
return result;

这有效,因为:

  • a ^ 0 = a,
  • a ^ a = 0
  • a ^ b = b ^ a
  • (a ^ b) ^ c = a ^ (b ^ c)

所以成对的数字相互抵消,无论它们出现在数组中的什么地方。


请注意,虽然这是一种非常不同的回答方法,但您可以应用类似的方法来使用 a Map

Map<Integer, Integer> map = new HashMap<>();
for (int n : nums) {
  if (!map.remove(n)) {
    map.add(n, n);
  }
}

这会在地图中添加和删除成对的项目;最后,地图中应该只剩下 1 个未配对的值。

return map.keySet().iterator().next();

(这里实际上没有理由使用 a Map,您不妨使用 a Set)。


推荐阅读