[Swift]Array(数组)扩展

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/ 
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10403543.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

扩展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]

 

转载于:https://www.cnblogs.com/strengthen/p/10403543.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值