题目是一个数组里只有唯一一个不重复的元素,其他元素都重复两次,输出唯一不重复的元素的值。
用哈希表写了以后不输出,求问!!
以下代码输出undefined:
class HashCode {
constructor() {
this.storage = []; //数组存放index
this.limit = 10;
this.count = 0;
}
hashFunc(num, max) {
let hashCode = 0;
for (i = 0; i < num.length; i++) {
hashCode = num[i];
}
let index = hashCode / max;
return hashCode;
}
put(key, value) {
// 根据哈希函数获取index值
const index1 = this.hashFunc(key, this.limit);
// 根据index值获取对应的链值
let bucket = this.storage[index1];
// 判断bucket是否为空
if (bucket === undefined) {
bucket = [];
this.storage[index1] = bucket;
}
// 判断是否修改数据
let overide = false;
for (let i = 0; i < bucket.length; i++) {
let tuple = bucket[i];
if (tuple[0] == key) {
tuple[1] = value;
// 如果bucket中有key属性,则令他对应的值为value
overide = true;
}
}
if (!overide) {
bucket.push([key, value]);
this.count++;
}
}
}
var hashIndex = new HashCode();
let index = 0;
var singleNumber = function (nums) {
for (i = 0; i < nums.length; i++) {
for (j = i; j < nums.length; j++) {
if (nums[i] == nums[j]) {
index++;
}
hashIndex = hashIndex.put(nums[i], index);
return hashIndex;
}
}
for (k = 0; k < hashIndex.length; k++) {
console.log(hashIndex.key);
}
};
let num = [1, 2, 2, 3, 3, 4, 4];
console.log(singleNumber(num));
a=[1,2,3,4,5,4,3,2,1];
result=null;
a.forEach(v=>{if(a.indexOf(v)===a.lastIndexOf(v)){result=v;}});
console.log(result);
//结果是5