217. 存在重复元素
Geekhyt opened this issue · 0 comments
Geekhyt commented
排序
排序后看相邻两位的数字
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
}