如何高效的判断数组中是否存在至少两个相同的数值,存在返回true,不存在返回false

来源:互联网 发布:同花顺手机行情软件 编辑:程序博客网 时间:2024/05/19 00:38

最普通最容易想到的方法是2次循环,代码如下:

public static boolean containsDuplicate(int[] nums) {                for(int n=0;n<nums.length-1;n++){        for(int m=n+1;m<nums.length;m++){        if(nums[n]==nums[m]){        return true;        }        }        }return false;}
缺点:过于暴力,执行效率低,如果数组特别庞大,运行时间过长。

在leetcode上看到一个效率很高的方法,用了Hashset,代码如下:
public  boolean containsDuplicate(int[] nums) {         Set<Integer> set = new HashSet<Integer>();         for(int i : nums)             if(!set.add(i))// if there is same                 return true;          return false;     }
关键字:hashset


0 0