leetcode探索 哈希表 存在重复元素

题目

给定一个整数数组,判断是否存在重复元素。
如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
示例 1:
输入: [1,2,3,1]
输出: true

https://leetcode-cn.com/explore/learn/card/hash-table/204/practical-application-hash-set/805/

分析

使用hashmap,循环时候,判断当前数值是否已经在map中了。

解法

func containsDuplicate(nums []int) bool {

    set := make(map[int]struct{})
    for _, v := range nums {
        if _, ok := set[v]; ok {
            return true
        }
        set[v] = struct{}{}
    }
    return false
}

你可能感兴趣的:(LeetCode探索,Go语言实现)