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

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

题目描述:

LeetCode217——存在重复元素

知识点:哈希表

思路:用一个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解题报告:

LeetCode217——存在重复元素

 

相关文章:

  • 2021-11-01
  • 2021-09-21
  • 2021-08-05
  • 2021-09-20
  • 2022-01-27
  • 2021-09-05
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-06-18
  • 2022-12-23
  • 2021-06-03
  • 2021-07-26
  • 2021-10-02
相关资源
相似解决方案