Find Duplicate Elements In Array Using Swift

后端 未结 12 1410
说谎
说谎 2020-11-29 01:42

How to find Duplicate Elements in Array? I have array of phone numbers so in the phone numbers i should start searching from the right side to the left side and find similar

12条回答
  •  醉话见心
    2020-11-29 01:55

    You could implement it using "Merge sort", but you need to make one modification, during the merge step you should ignore the duplicates.

    The easiest way to find duplicate elements is if the phone number is just a 6-digit number and has type Int, you could sort the array of phone numbers and than filter that to find duplicates.

    var phoneNumbers = [123456, 234567, 345678, 123456, 456789, 135790, 456789, 142638]
    
    func findDuplicates(sortedArray array: [Int]) -> [Int]
    {
        var duplicates: [Int] = []
    
        var prevItem: Int = 0
        var addedItem: Int = 0
    
        for item in array
        {
            if(prevItem == item && addedItem != item)
            {
                duplicates.append(item)
                addedItem = item
            }
    
            prevItem = item
        }
    
        return duplicates
    }
    
    func sortPhoneNumbers(phoneNumbers: [Int]) -> [Int]
    {
        return phoneNumbers.sorted({ return $0<$1 })
    }
    
    sortPhoneNumbers(phoneNumbers)
    findDuplicates(sortPhoneNumbers(phoneNumbers))
    

    In addition, you could implement the findDuplicates method in different ways:

    Using Set (Swift 1.2+):

    func findDuplicates(array: [Int]) -> [Int]
    {
        var duplicates = Set()
        var prevItem = 0       
    
        for item in array
        {
            if(prevItem == item)
            {
                duplicates.insert(item)
            }
    
            prevItem = item
        }
    
        return Array(duplicates)
    }
    

    And so on.

提交回复
热议问题