Skip to content

217. 存在重复元素 #88

Description

@Geekhyt

原题链接

排序

排序后看相邻两位的数字

const containsDuplicate = function(nums) {
    nums.sort((a, b) => a - b)
    const n = nums.length
    for (let i = 0; i < n - 1; i++) {
        if (nums[i] === nums[i + 1]) {
            return true
        }
    }
    return false
}
  • 时间复杂度:O(nlogn)
  • 空间复杂度:O(logn)

哈希表

const containsDuplicate = function(nums) {
    const set = new Set()
    for (const x of nums) {
        if (set.has(x)) {
            return true
        }
        set.add(x)
    }
    return false
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

一行代码

const containsDuplicate = function(nums) {
    return new Set(nums).size !== nums.length
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions