- Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathArray.swift
More file actions
Latest commit
103 lines (92 loc) · 2.47 KB
/
Copy pathArray.swift
File metadata and controls
103 lines (92 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//
// Array.swift
// Array
//
// Created by ggl on 2019/3/20.
// Copyright © 2019年 ggl. All rights reserved.
// 大小固定的有序动态扩容数组
import Foundation
classDynamicExpansionArray{
/// 数组底层存储结构
vararray:UnsafeMutablePointer<Int>
/// 数组元素个数
varsize:Int
/// 数组容量大小
varcapcity:Int
/// 初始化方法
///
/// - Parameter capcity: 数组容量大小
init(capcity:Int){
size =0
self.capcity = capcity
array = UnsafeMutablePointer<Int>.allocate(capacity: capcity)
array.initialize(repeating:Int.min, count: capcity)
}
/// 增加元素
///
/// - Parameter num: 要增加的数字
func add(num:Int){
if size >= capcity {
lettempArray= array
array = UnsafeMutablePointer<Int>.allocate(capacity: capcity *2)
array.initialize(repeating:Int.min, count: capcity *2)
array.assign(from: tempArray, count: size)
tempArray.deallocate()
capcity *=2
}
array[size]= num
size +=1
}
/// 插入元素
///
/// - Parameters:
/// - num: 要增加的数字
/// - at: 位置下标
/// - Returns: 插入是否成功
@discardableResult
func insert(num:Int, at index:Int)->Bool{
if index <0{
Swift.print("下标位置错误")
returnfalse
}
add(num: num)
if index < size -1{
//交换位置
letpNum=array[index]
array[index]= num
array[size-1]= pNum
}
returntrue
}
/// 删除元素
///
/// - Parameter at: 位置下标
/// - Returns: 是否成功
@discardableResult
func remove(at index:Int)->Bool{
if index <0 || index >= size {
returnfalse
}
foriin index..<size-1{
array[i]=array[i+1]
}
size -=1
returntrue
}
/// 打印元素
func print(){
Swift.print("[", terminator:"")
foriin0..<size {
if i == size -1{
Swift.print(array[size-1], terminator:"]")
}else{
Swift.print(array[i], terminator:"")
}
}
Swift.print("")
}
deinit{
array.deinitialize(count: capcity)
array.deallocate()
}
}