ArraySet 1.0.4

ArraySet 1.0.4

Lazar Otasevic 维护。



ArraySet 1.0.4

ArraySet

这是Swift语言实现的ArraySet。ArraySet是一种数据结构,其中的元素是唯一的并且是有序的,您可以使用以下方式:

  • 直接使用下标读取元素 - 就像Array
  • 插入和删除元素 - 就像Set
  • 以O(log N)的时间复杂度找到给定元素的索引

实现基于维持内部有序数组和防止重复。

基本协议

public protocol SortedCollection {
    associatedtype Element: Comparable
    var sortedElements: [Element] { get }
}

public protocol MutableIndexReversableCollection {
    associatedtype Element
    mutating func remove(at index: Int) -> Element
    mutating func insert(_ element: Element) -> Int
    mutating func remove(_ element: Element) -> Int?
}

public protocol IndexReversableCollection {
    associatedtype Element
    func firstIndex(of element: Element) -> Int?
    func lastIndex(of element: Element) -> Int?
}

public protocol UniqueIndexReversableCollection {
    associatedtype Element
    func index(of element: Element) -> Int?
}

复合协议

protocol SortedArrayProtocol:
    RandomAccessCollection,
    SortedCollection,
    MutableIndexReversableCollection,
    IndexReversableCollection {}

protocol ArraySetProtocol:
    RandomAccessCollection,
    SortedCollection,
    MutableIndexReversableCollection,
    UniqueIndexReversableCollection {}

示例

使用ArraySet

        let arraySet = ArraySet(elements: [1, 2, 0, 2])
        XCTAssertEqual(arraySet.sortedElements, [0, 1, 2])

使用SortedArray

        let sortedArray = SortedArray(elements: [1, 2, 1])
        XCTAssertEqual(sortedArray.sortedElements, [1, 1, 2])