how to find duplicate values in integer array by loop in swift?

风流意气都作罢 提交于 2021-01-28 21:11:14

问题


I need to know how to find duplicate values in integer array by loop method in swift? I tried to ->

func findDuplicates (array: [Int]) {
        var prevItem = array[0]
        for i in 0...array.count-1 {
            if prevItem == array[i] {
                print(i)
            } else {
               print("there is no any duplicates values")
            }
        }
}

please show my solution in this way!


回答1:


You can use a set and every time you try to insert an element it fails it means it is a duplicate. You would need also to make sure you don't keep duplicate elements on the result:

func findDuplicates (array: [Int]) {
    var set: Set<Int> = []
    for i in array {
        if !set.insert(i).inserted {
            print("duplicate element:", i)
        }
    }
}

findDuplicates(array: [1,2,3,4,5,6,5,6,7,9])

This will print:

duplicate element: 5
duplicate element: 6

If you would like to return all duplicate elements of a collection you can simply use filter:

func getDuplicates(in array: [Int]) -> [Int] {
    var set: Set<Int> = []
    var filtered: Set<Int> = []
    return array.filter { !set.insert($0).inserted && filtered.insert($0).inserted }
}

getDuplicates(in: [1,2,3,4,5,6,5,6,7,9])  // [5, 6]


extension RangeReplaceableCollection where Element: Hashable {
    var duplicates: Self {
        var set: Set<Element> = []
        var filtered: Set<Element> = []
        return filter { !set.insert($0).inserted && filtered.insert($0).inserted }
    }
}

let numbers = [1,2,3,4,5,6,5,6,7,9]
numbers.duplicates                   // [5, 6]

let string = "1234565679"
string.duplicates                    // "56"


来源:https://stackoverflow.com/questions/65295137/how-to-find-duplicate-values-in-integer-array-by-loop-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!