Skip to content

Latest commit

 

History

History
41 lines (34 loc) · 1018 Bytes

217.存在重复元素.md

File metadata and controls

41 lines (34 loc) · 1018 Bytes

217.存在重复元素

/*
 * @lc app=leetcode.cn id=217 lang=typescript
 *
 * [217] 存在重复元素
 */

// @lc code=start
function containsDuplicate(nums: number[]): boolean {}
// @lc code=end

解法 1: 使用哈希表

  • 时间复杂度: O(n)
  • 空间复杂度: O(n)
function containsDuplicate(nums: number[]): boolean {
  const cache = new Set()
  for (const num of nums) {
    if (cache.has(num)) return true
    cache.add(num)
  }
  return false
}

Case

test.each([
  { input: { nums: [1, 2, 3, 1] }, output: true },
  { input: { nums: [1, 2, 3, 4] }, output: false },
  { input: { nums: [1, 1, 1, 3, 3, 4, 3, 2, 4, 2] }, output: true },
])('input: nums = $input.nums', ({ input: { nums }, output }) => {
  expect(containsDuplicate(nums)).toEqual(output)
})