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 return true 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 }
原文地址:https://www.cnblogs.com/strengthen/p/9745536.html
时间: 2024-11-06 07:48:33