[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 }
相關文章
相關標籤/搜索