Contains Duplicate

View on LeetCode

Question

You're given a list of numbers. You need to check whether any value appears more than once.

Return true if any number is repeated. Otherwise, return false.

Example

Input: [1, 2, 3, 4]

Output: false

Explanation: All numbers are unique.


Input: [3, 1, 2, 3]

Output: true

Explanation: The number 3 appears twice.


Input: [7]

Output: false

Explanation: Only one element.

My Notes

Why use struct{} and not bool?

package main

import (
    "fmt"
)

func main() {
    result := containsDuplicate([]int{1,2,3,4,4,5,6,7})
    fmt.Println(result)
}

func containsDuplicate(nums []int) bool {
    lookup := make(map[int]struct{})

    for _, item := range nums {
        if _, ok := lookup[item]; ok {
            return true
        }
        lookup[item] = struct{}{}
    }
    return false
}