在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 扩展Array 1 extension Array where Element : Equatable { 2 //获取数组中的指定元素的索引值 3 //Parameter item: 元素 4 //Returns: 索引值数组 5 public func indexes(_ item: Element) -> [Int] { 6 var indexes = [Int]() 7 for index in 0..<count where self[index] == item { 8 indexes.append(index) 9 } 10 return indexes 11 } 12 13 //获取元素首次出现的位置 14 //Parameter item: 元素 15 //Returns: 索引值 16 public func firstIndex(_ item: Element) -> Int? { 17 for (index, value) in lazy.enumerated() where value == item { 18 return index 19 } 20 return nil 21 } 22 23 //获取元素最后出现的位置 24 //Parameter item: 元素 25 //Returns: 索引值 26 public func lastIndex(_ item: Element) -> Int? { 27 return indexes(item).last 28 } 29 30 //删除数组中的指定元素 31 //Parameter object: 元素 32 public mutating func remove(_ object:Element) -> Void { 33 for idx in self.indexes(object).reversed() { 34 self.remove(at: idx) 35 } 36 } 37 } 测试代码: 1 var arr:[Int] = [1,2,3,4,5,5,6,7,7,8,9,10] 2 print(arr.firstIndex(5)) 3 //Prnt Optional(4) 4 print(arr.lastIndex(7)) 5 //Prnt Optional(8) 6 arr.remove(7) 7 print(arr) 8 //Prnt [1, 2, 3, 4, 5, 5, 6, 8, 9, 10] 扩展数组,二分法插入: 1 private extension Array where Element: Comparable { 2 private func binarySearchIndex(for element: Element) -> Int { 3 var min = 0 4 var max = count 5 while min < max { 6 let index = (min+max)/2 7 let other = self[index] 8 if other == element { 9 return index 10 } else if other < element { 11 min = index+1 12 } else { 13 max = index 14 } 15 } 16 return min 17 } 18 19 mutating func binaryInsert(_ element: Element) { 20 insert(element, at: binarySearchIndex(for: element)) 21 } 22 } 测试代码: 1 var arr:[Int] = [1,2,3,4,5,6,7,8,9] 2 arr.binaryInsert(5) 3 print(arr) 4 //Print [1, 2, 3, 4, 5, 5, 6, 7, 8, 9]
|
请发表评论