Find Duplicate Elements In Array Using Swift

后端 未结 12 1397
说谎
说谎 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 02:03

    I also had a similar problem and have overcome in the following way. (Xcode 8.3.2)

    let a = [123456, 234567, 345678, 123456, 456789, 135790, 456789, 142638]
    var b = a // copy-on-write so that "a" won't be modified
    
    while let c = b.popLast() {
      b.forEach() {
        if $0 == c {
          Swift.print("Duplication: \(c)")
        }
      }
    }
    
    //  Duplication: 456789
    //  Duplication: 123456
    

    The point is that the number of comparison. It would be smaller than others.

    Assume that the number of items in the array is N. In each loop, the number will be decrementing by one. So, the total number will be (N-1) + (N-2) + (N-3) + ... + 2 + 1 = N * (N-1) / 2 When N = 10, that will be 9 + 8 + ... = 45

    In contrast, that of some algorithms might be N * N. When N = 10 that will be 100.

    In spite of that, taking into account of the cost of deep-copy or shallow-copy, I agree that @Patrick Perini's brilliant way would be better than this in some situations even the number of that would be N * N.

    EDIT:

    Alternative way with IteratorProtocol

    let a = [123456, 234567, 345678, 123456, 456789, 135790, 456789, 142638]
    var i = a.makeIterator()
    
    while let c = i.next() {
      var j = i
      while let d = j.next() {
        if c == d {
          Swift.print("Duplication: \(c)")
        }
      }
    }
    
    //  Duplication: 123456
    //  Duplication: 456789
    

    That looks more complex, but uses the same idea as before. This does not have unnecessary memory allocations or copies.

    My concern is efficiency, i.e. quicker UI response, longer battery life, smaller memory footprint, etc. Avoiding unnecessary memory allocations and/or memory copies which are automatically done by Swift in the behind scene would be crucial if we are providing competitive products. (-;

提交回复
热议问题