LeetCode217——存在重复元素

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/contains-duplicate/description/

题目描述:

知识点:哈希表
思路:用一个HashSet来存储已遍历元素

一旦发现重复元素即返回true,如果遍历结束还未发现重复元素,说明数组中不存在重复元素,返回false。

时间复杂度和空间复杂度均是O(n),其中n为数组的长度。

JAVA代码:

    public class Solution {
        public boolean containsDuplicate(int[] nums) {
            Set<Integer> set = new HashSet<>();
            for (int i = 0; i < nums.length; i++) {
                if(set.contains(nums[i])) {
                    return true;
                }else{
                    set.add(nums[i]);
                }
            }
            return false;
        }
    }

LeetCode解题报告:

 
---------------------
作者:清風逐尘乀
来源:CSDN
原文:https://blog.csdn.net/qq_41231926/article/details/86763123
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2019-07-06 18:15  天涯海角路  阅读(72)  评论(0)    收藏  举报