[Swift]LeetCode217. 存在重复元素 | Contains Duplicate

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-opallvnq-md.html 
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given an array of integers, find if the array contains any duplicates.git

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.github

Example 1:数组

Input: [1,2,3,1]
Output: true

Example 2:微信

Input: [1,2,3,4]
Output: false

Example 3:app

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true

给定一个整数数组,判断是否存在重复元素。函数

若是任何值在数组中出现至少两次,函数返回 true。若是数组中每一个元素都不相同,则返回 false。spa

示例 1:code

输入: [1,2,3,1]
输出: true

示例 2:htm

输入: [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 }
相关文章
相关标签/搜索