Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

217. 存在重复元素 #88

Open
Geekhyt opened this issue Sep 20, 2021 · 0 comments
Open

217. 存在重复元素 #88

Geekhyt opened this issue Sep 20, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Sep 20, 2021

原题链接

排序

排序后看相邻两位的数字

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
}
@Geekhyt Geekhyt added the 简单 label Sep 20, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant