检查数组是否包含重复值 [英] Check if an array contains duplicate values

查看:122
本文介绍了检查数组是否包含重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个javascript函数来检查数组是否包含重复值。

I wanted to write a javascript function which checks if array contains duplicate values or not.

我写了以下代码,但它的答案为true总是。

I have written the following code but its giving answer as "true" always.

任何人都可以告诉我我错过了什么。

Can anybody please tell me what am I missing.

function checkIfArrayIsUnique(myArray) 
    {
        for (var i = 0; i < myArray.length; i++) 
        {
            for (var j = 0; j < myArray.length; j++) 
            {
                if (i != j) 
                {
                    if (myArray[i] == myArray[j]) 
                    {
                        return true; // means there are duplicate values
                    }
                }
            }
        }
        return false; // means there are no duplicate values.
    }


推荐答案

你得到了返回值错误的回合:

You got the return values the wrong way round:


  • 一旦找到两个相等的值,就可以得出结论,该数组是唯一并返回 false

最后,在你结束之后检查了所有对,你可以返回 true

At the very end, after you've checked all the pairs, you can return true.

如果你这么做,并且数组很大,你可能想要研究对数组进行排序然后只比较相邻元素的可能性。这将比您当前的方法具有更好的渐近复杂度。

If you do this a lot, and the arrays are large, you might want to investigate the possibility of sorting the array and then only comparing adjacent elements. This will have better asymptotic complexity than your current method.

这篇关于检查数组是否包含重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆