Content-Length: 258349 | pFad | https://github.com/Geekhyt/javascript-leetcode/issues/88

17 217. 存在重复元素 · Issue #88 · Geekhyt/javascript-leetcode · GitHub
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









      ApplySandwichStrip

      pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


      --- a PPN by Garber Painting Akron. With Image Size Reduction included!

      Fetched URL: https://github.com/Geekhyt/javascript-leetcode/issues/88

      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy