从Swift中的数组数组中删除较小的值集

时间:2016-06-02 23:49:19

标签: arrays swift

给定一个由包含整数的数组组成的数组。

[[2], [3], [2, 2], [5], [7], [2, 2, 2], [3, 3]]

Swift中首选的方法是删除包含少量具有特定值的元素的数组,并仅保留包含该值的较大数组。

上面输入的结果是

[[5], [7], [2, 2, 2], [3, 3]]

3 个答案:

答案 0 :(得分:2)

使用[Int: [Int]]字典跟踪密钥指定值的最大数组。

let arrays = [[2], [3], [2, 2], [5], [7], [2, 2, 2], [3, 3]]
var largest = [Int: [Int]]()

for arr in arrays {
    // Get the first value from the array
    if let first = arr.first {

        // current is the count for that key already in dictionary largest
        // If the key isn't found, the nil coalescing operator ?? will
        // return the default count of 0.
        let current = largest[first]?.count ?? 0

        // If our new array has a larger count, put it in the dictionary
        if arr.count > current {
            largest[first] = arr
        }
    }
}

// Convert the dictionary's values to an array for the final answer.   
let result = Array(largest.values)

print(result)  // [[5], [7], [2, 2, 2], [3, 3]]

同样的逻辑可以与reduce一起使用,以便在一行中提供结果:

let result = arrays.reduce([Int: [Int]]()) { var d = $0; guard let f = $1.first else { return d }; d[f] = d[f]?.count > $1.count ? d[f] : $1; return d }.map { $1 }

替代版本

此版本使用[Int: Int]字典来保存为每个键找到的最大数组的计数,然后使用数组构造函数在末尾重建数组。

let arrays = [[2], [3], [2, 2], [5], [7], [2, 2, 2], [3, 3]]
var counts = [Int: Int]()

for arr in arrays {
    if let first = arr.first {
        counts[first] = max(counts[first] ?? 0, arr.count)
    }
}

let result = counts.map { [Int](count: $1, repeatedValue: $0) }

print(result)  // [[5], [7], [2, 2, 2], [3, 3]]

同样的逻辑可以与reduce一起使用,以便在一行中提供结果:

let result = arrays.reduce([Int: Int]()) { var d = $0; guard let f = $1.first else { return d }; d[f] = max(d[f] ?? 0, $1.count); return d }.map { [Int](count: $1, repeatedValue: $0) }

答案 1 :(得分:1)

当我看到vacawama回应了一些非常相似的东西时,我正准备写下我的答案。决定回到它虽然只是因为它是一个有趣的问题。所以我的替代方案几乎肯定比vacawama的解决方案慢得多,并且没有保留顺序,但我认为这是一个有趣的例子,你可以用来解决Swift中的这类问题。

var items = [[2], [3], [2, 2], [5], [7], [2, 2, 2], [3, 3]]

let reduced = items.sort({
        let lhs = $0.first, rhs = $1.first
        return lhs == rhs ? $0.count > $1.count : lhs < rhs
    }).reduce( [[Int]]()) { (res, items) in
        return res.last?.last != items.last ? res + [items] : res
    }

print(reduced)  // [[2, 2, 2], [3, 3], [5], [7]]

或者如果你想把所有这些都塞进一行:

var items = [[2], [3], [2, 2], [5], [7], [2, 2, 2], [3, 3]]

let reduced = items.sort({ let lhs = $0.first, rhs = $1.first; return lhs == rhs ? $0.count > $1.count : lhs < rhs }).reduce([[Int]]()) { $0.last?.last != $1.last ? $0 + [$1] : $0 }

print(reduced)  // [[2, 2, 2], [3, 3], [5], [7]]

答案 2 :(得分:0)

使用forEach只是另一种选择:

let arrays = [[2],  [2, 2], [5], [7], [2, 2, 2], [3, 3], [3]]
var largest: [Int: [Int]] = [:]

arrays.forEach({
    guard let first = $0.first else { return }
    largest[first] = [Int](count: max($0.count,largest[first]?.count ?? 0), repeatedValue: first)
})
Array(largest.values)  // [[5], [7], [2, 2, 2], [3, 3]]