LeetCode217-存在重复元素

 

非商业,LeetCode链接附上:

https://leetcode-cn.com/problems/contains-duplicate/

进入正题。

 

题目:

给定一个整数数组,判断是否存在重复元素。

如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。

示例:

输入: [1,2,3,1]
输出: true
输入: [1,2,3,4]
输出: false

代码实现:

    /**
     * 方法一
     * @param nums
     * @return
     */
    public static boolean containsDuplicate(int[] nums) {

        Set<Integer> hashSet = new HashSet<>();
        for (int num : nums) {
            hashSet.add(num);
        }

        return hashSet.size() < nums.length;
    }


    /**
     * 方法二
     * @param nums
     * @return
     */
    public static boolean containsDuplicate(int[] nums) {

        Set<Integer> hashSet = new HashSet<>();
        for (int num : nums) {
            if (hashSet.contains(num)) return true;
            hashSet.add(num);
        }
        return false;
    }

    //时间复杂度O(n),空间复杂度O(n)

  

分析:

首先,这里只是哈希表两种写法的区别对比,区别并不大,但还是有区别,一种是遍历所有得到长度进行对比,一种是对比是否含有相同元素,相同即返回。

(在LeetCode的解析里有其他的方法,可以去查阅参考,链接在文章头部)

这里用这道题目想说明的也是,解决方法可能有很多种,在实际的生产中如何选择,可以结合数据量大小等实际情况。

算法还是挺重要的,时间和空间复杂度都比较优的解法是很有意义的。

 

--End

 

posted @ 2020-11-18 15:06  黑冰台  阅读(95)  评论(0)    收藏  举报