217. 存在重復元素 | Contains Duplicate
阿新 • • 發佈:2018-10-05
class dup duplicate indices 返回 element and 一個 style
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
1 class Solution { 2 func containsDuplicate(_ nums: [Int]) -> Bool {3 if nums == nil || nums.count == 0 {return false} 4 var array:[Int] = nums 5 //先排序 6 array.sort(){$0 < $1} 7 //再遍歷 8 for i in 0..<(array.count-1) 9 { 10 if array[i] == array[i+1] 11 { 12 returntrue 13 } 14 } 15 return false 16 } 17 }
36ms
1 class Solution { 2 func containsDuplicate(_ nums: [Int]) -> Bool { 3 var set = Set<Int>() 4 5 for index in nums.indices where !set.insert(nums[index]).inserted{ 6 return true 7 } 8 return false 9 } 10 }
40ms
1 class Solution { 2 func containsDuplicate(_ nums: [Int]) -> Bool { 3 var set = Set(nums) 4 return set.count != nums.count 5 } 6 }
217. 存在重復元素 | Contains Duplicate