[Swift]LeetCode217. 存在重复元素 | Contains Duplicate
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9745536.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1] Output: true
Example 2:
Input: [1,2,3,4] Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2] Output: true
给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
示例 1:
输入: [1,2,3,1] 输出: true
示例 2:
输入: [1,2,3,4] 输出: false
示例 3:
输入: [1,1,1,3,3,4,3,2,4,2] 输出: true
168ms
1 class Solution { 2 func containsDuplicate(_ nums: [Int]) -> Bool { 3 return Set(nums).count != nums.count 4 } 5 }
176ms
1 class Solution { 2 func containsDuplicate(_ nums: [Int]) -> Bool { 3 4 if nums.count == 0 { 5 return false 6 } 7 8 var dict: Set<Int> = Set() 9 10 for item in nums { 11 dict.insert(item) 12 } 13 14 if dict.count < nums.count { 15 return true 16 } 17 18 19 return false 20 } 21 }
180ms
1 class Solution { 2 func containsDuplicate(_ nums: [Int]) -> Bool { 3 guard nums.count > 1 else { 4 return false 5 } 6 var set = Set([Int]()) 7 for num in nums { 8 if set.contains( num) { 9 return true 10 } else { 11 set.insert(num) 12 } 13 } 14 return false 15 } 16 }