数组示例:[ "Apple", "computer", "Apple", "Bag" ]
我必须创建一个获取第一个唯一值的函数,在这种情况下,**computer**
这是我的工作解决方案:
function firstUniqueProduct(products) {
for (var index = 0; index < products.length; index++) {
var product = products[index];
var isUnique = true;
for (var index2 = 0; index2 < products.length; index2++) {
var product2 = products[index2];
if (product === product2 && index !== index2) {
isUnique = false;
break;
}
}
if (isUnique) return product;
}
return null;
}
console.log(firstUniqueProduct([ "Apple", "computer", "Apple", "Bag" ]));
一个拥抱数组需要花费很多时间,任何人都可以为我提供更好的算法。
您可以创建两个Set:一组用于到目前为止已发现的元素,而另一组用于到目前为止已发现两次或更多的元素。迭代时,如果尚不存在,请将其放在第一组中。否则,将其从第一个中删除,然后放入第二个中。最后,取第一个集合中的第一个值(如果集合中没有元素,则为null)
function firstUniqueProduct(products) {
const foundOnce = new Set();
const foundTwice = new Set();
for (const elm of products) {
if (foundTwice.has(elm)) continue;
if (foundOnce.has(elm)) {
foundOnce.delete(elm);
foundTwice.add(elm);
} else {
foundOnce.add(elm);
}
}
return foundOnce.size ? [...foundOnce][0] : null;
}
console.log(firstUniqueProduct([ "Apple", "computer", "Apple", "Bag" ]));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句