【问题标题】:How to compare two arrays and remove matching elements from one array in Swift iOS如何在 Swift iOS 中比较两个数组并从一个数组中删除匹配的元素
【发布时间】:2020-03-28 07:34:44
【问题描述】:

我有两个数组。

let array1 = ["Lahari", "Vijayasri"];
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"];

我想删除array2中的array1元素并打印最终的类似数组

result array = ["Ramya", "Keerthi"]

【问题讨论】:

  • 输出数组的顺序重要吗? array1 是否保证与array2 的顺序相同,并且只包含array2 中的元素?
  • 为了澄清,如果array1["Vijayasri", "Lahari", "Vijayasri"]array2["Lahari", "Vijayasri", "Ramya", "Keerthi", "Lahari"],结果应该是什么?

标签: ios arrays swift


【解决方案1】:

将数组转换为Sets 并使用subtract 是一种简单有效的方法:

let array1 = ["Lahari", "Vijayasri"]
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"]

let resultArray = Array(Set(array2).subtracting(Set(array1)))

如果保持array2 的顺序很重要,那么您可以将filter 与集合一起使用-

let compareSet = Set(array1)

let resultArray = array2.filter { !compareSet.contains($0) }

【讨论】:

  • 这不能保持秩序。
  • 保留订单不是规定的要求
  • 我想这取决于你对“喜欢”的解释! ?
  • 好吧,对不起,删除我的评论;)
【解决方案2】:

Paulw11 回答完美。但是如果在数组中排序很重要,你可以这样做:

let reuslt = array2.filter { !array1.contains($0) }

【讨论】:

  • 值得注意的是,这确实保留了顺序,但代价是 O(n^2)
  • 使用 Set 有更好的性能,但这样排序是主要目标
【解决方案3】:
extension Array where Element: Hashable {
    func difference(from other: [Element]) -> [Element] {
        let thisSet = Set(self)
        let otherSet = Set(other)
        return Array(thisSet.subtracting(otherSet))
    }
}

var array1 = ["Lahari", "Vijayasri"]
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"]
let a = array2.difference(from: array1) // ["Ramya", "Keerthi"]

【讨论】:

    【解决方案4】:

    只取结尾。

    array2[array1.count...]
    

    【讨论】:

    • ? 在你的 -1。它通过了所有测试!
    • 对于问题中的数据,是的。但是如果array2["John","Lahari", "Vijayasri", "Ramya", "Keerthi"]array1 不变呢?你需要一个通用的解决方案,否则你可以直接说resultArray = ["Ramya", "Keerthi"] 就可以了。
    • 我们拭目以待。我看着它,发现第一个是第二个的有序子集的问题。没有足够的信息来了解必要的解决方案是什么,但我的代码比字符串数组文字短!
    • 对我来说,您所做的假设比需要保留订单要大得多。
    • 我们认为什么并不重要。只有一组更好的测试可以提供帮助。事实上,我的保证会通过,而你的不会!
    猜你喜欢
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多