【问题标题】:how to find duplicate values in integer array by loop in swift? [closed]如何在swift中循环查找整数数组中的重复值?
【发布时间】:2021-03-25 10:53:27
【问题描述】:

我需要知道如何在 swift 中通过循环方法在整数数组中查找重复值? 我试图 ->

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")
            }
        }
}

请以这种方式展示我的解决方案!

【问题讨论】:

  • 您需要知道重复值还是想知道是否有重复值?
  • 我想知道,如何循环查找重复值?

标签: arrays swift for-loop foreach swift3


【解决方案1】:

您可以使用集合,每次尝试插入元素时都会失败,这意味着它是重复的。您还需要确保不会在结果中保留重复的元素:

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])

这将打印:

重复元素:5
重复元素:6

如果你想返回一个集合的所有重复元素,你可以简单地使用过滤器:

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"

【讨论】:

  • 这是一个很好的解决问题的方法,大致有O(n)的性能。 (很容易写出O(n²) 性能的解决方案,这很糟糕。)
  • @DuncanC 实际上我们需要添加第二个检查以避免在结果集合中出现重复
猜你喜欢
  • 2016-08-04
  • 1970-01-01
  • 2014-05-20
  • 2012-05-04
  • 1970-01-01
  • 2018-07-28
  • 1970-01-01
  • 2011-12-18
  • 2010-12-27
相关资源
最近更新 更多