当前位置:网站首页>[daily exercise] 217 Duplicate element exists

[daily exercise] 217 Duplicate element exists

2022-06-11 05:46:00 swindler.

Given an array of integers , Determine whether there are duplicate elements .

If a value exists, it appears at least twice in the array , The function returns true . If every element in the array is different , Then return to false .

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

class Solution {
    
    func containsDuplicate(_ nums: [Int]) -> Bool {
    
        var dict = [Int:Int]()
        for num in nums {
    
            if dict[num] != nil {
    
                return true
            }else {
    
                dict[num] = 1
            }
        }
    return false
    }
}

Their thinking : First create a storage nums A dictionary of values and occurrences , And then iterate through the array , Assign the first occurrence of the element key to 1, In the process of traversal , Value is empty (nil) The value of is that the element that has not been assigned value appears only once ; If the value is not empty, it is the element that has been previously assigned , That is, find the elements that appear more than once .

原网站

版权声明
本文为[swindler.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020534563035.html