[LeetCode] NO.217 Contains Duplicate

[题目] Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

 

[题目解析] 直接想到的方法是用hash,遍历记录数组中每个元素出现的次数,当有元素出现次数大于1时返回true,否则返回false。此外,可以用Set不包含重复元素的特征,代码如下。

    public boolean containsDuplicate(int[] nums) {
        if(nums.length == 0) return false;
        Set<Integer> set = new HashSet<Integer>();
        for(int num : nums){
          set.add(num);
        }
        return !(set.size() == nums.length);
    }

其实也可以用bit-map + hash的方法,不过要消耗掉好大的空间。

另外还有一种思路是对数组先进行排序,然后遍历,比较相邻元素是否相等来判断是否含有重复元素。

posted @ 2016-08-18 19:45  三刀  阅读(102)  评论(0编辑  收藏  举报