快速从单个数组获取重复值

时间:2019-06-03 09:04:05

标签: arrays swift

我是iOS的新手,请尝试一些方法,你们可以帮助我。感谢您的帮助

let values = ["sid","sid","tarun","nitesh"]

输出必须为:

["sid","sid"]

2 个答案:

答案 0 :(得分:2)

检查数组中每个元素的计数,如果计数大于1,则在结果数组中追加

let values = ["sid","sid","tarun","nitesh","nitesh"]
var result = [String]()
values.forEach { value in
    if values.filter({ $0 == value }).count > 1 {
        result.append(value)
    }
}
print(result)//["sid", "sid", "nitesh", "nitesh"]

OR

let result = values.filter { value in values.filter({ $0 == value }).count > 1  }
print(result)

答案 1 :(得分:2)

一种有效的解决方案是首先创建“字数”或“直方图”。遍历数组一次,并为每个值更新字典:

let values = ["sid", "sid", "tarun", "nitesh"]

let wordcount = values.reduce(into: [:]) { (dict, value) in
    dict[value, default: 0] += 1
}

在您的示例中,该字典为["nitesh": 1, "sid": 2, "tarun": 1]

然后使用该字典过滤数组,并仅保留单词数大于1的条目。这需要再次遍历数组:

let duplicates = values.filter { wordcount[$0, default: 0] > 1 }
print(duplicates) // ["sid", "sid"]

总复杂度在数组元素数量中是 linear