Skip to content

217. 存在重复元素 #88

@Geekhyt

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy