1

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!

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571

2 Answers2

5

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"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • This is a very good solution to the problem, and has roughly `O(n)` performance. (it is easy to write a solution with `O(n²)` performance, which is terrible.) – Duncan C Dec 14 '20 at 19:51
  • @DuncanC Actually we need to add a second check to avoid having duplicates in the resulting collection – Leo Dabus Jan 09 '21 at 19:14
0
let list = [5,7,1,1,7,9]

var result : [Int] = []
var duplicateArr : [Int] = []

for i in 0..<list.count {
    var isDuplicate = false
    if duplicateArr.count == 0 {
        duplicateArr.append(list[i])
    }else{
        print(list[i])
         for j in 0..<duplicateArr.count{
             if duplicateArr[j] == list[i] {
                 isDuplicate = true
             }
         }
        if isDuplicate {
            result.append(list[i])
        }else{
            duplicateArr.append(list[i])
        }
    }
}
print("Duplicate list -> \(result))
ShAnTh
  • 1
  • 2
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 18 '22 at 02:03