feat: add Swift codes for array article

This commit is contained in:
nuomi1
2023-01-05 21:16:05 +08:00
parent 0e49f0053a
commit f49c674029
3 changed files with 196 additions and 0 deletions

View File

@ -9,6 +9,7 @@ let package = Package(
.executable(name: "worst_best_time_complexity", targets: ["worst_best_time_complexity"]),
.executable(name: "space_complexity", targets: ["space_complexity"]),
.executable(name: "leetcode_two_sum", targets: ["leetcode_two_sum"]),
.executable(name: "array", targets: ["array"]),
],
targets: [
.target(name: "utils", path: "utils"),
@ -16,5 +17,6 @@ let package = Package(
.executableTarget(name: "worst_best_time_complexity", path: "chapter_computational_complexity", sources: ["worst_best_time_complexity.swift"]),
.executableTarget(name: "space_complexity", dependencies: ["utils"], path: "chapter_computational_complexity", sources: ["space_complexity.swift"]),
.executableTarget(name: "leetcode_two_sum", path: "chapter_computational_complexity", sources: ["leetcode_two_sum.swift"]),
.executableTarget(name: "array", path: "chapter_array_and_linkedlist", sources: ["array.swift"]),
]
)

View File

@ -0,0 +1,103 @@
/**
* File: array.swift
* Created Time: 2023-01-05
* Author: nuomi1 (nuomi1@qq.com)
*/
//
func randomAccess(nums: [Int]) -> Int {
// [0, nums.count)
let randomIndex = nums.indices.randomElement()!
//
let randomNum = nums[randomIndex]
return randomNum
}
//
func extend(nums: [Int], enlarge: Int) -> [Int] {
//
var res = Array(repeating: 0, count: nums.count + enlarge)
//
for i in nums.indices {
res[i] = nums[i]
}
//
return res
}
// index num
func insert(nums: inout [Int], num: Int, index: Int) {
// index
for i in sequence(first: nums.count - 1, next: { $0 > index + 1 ? $0 - 1 : nil }) {
nums[i] = nums[i - 1]
}
// num index
nums[index] = num
}
// index
func remove(nums: inout [Int], index: Int) {
let count = nums.count
// index
for i in sequence(first: index, next: { $0 < count - 1 - 1 ? $0 + 1 : nil }) {
nums[i] = nums[i + 1]
}
}
//
func traverse(nums: [Int]) {
var count = 0
//
for _ in nums.indices {
count += 1
}
//
for _ in nums {
count += 1
}
}
//
func find(nums: [Int], target: Int) -> Int {
for i in nums.indices {
if nums[i] == target {
return i
}
}
return -1
}
@main
enum _Array {
// Driver Code
static func main() {
//
let arr = Array(repeating: 0, count: 5)
print("数组 arr = \(arr)")
var nums = [1, 3, 2, 5, 4]
print("数组 nums = \(nums)")
// 访
let randomNum = randomAccess(nums: nums)
print("在 nums 中获取随机元素 \(randomNum)")
//
nums = extend(nums: nums, enlarge: 3)
print("将数组长度扩展至 8 ,得到 nums = \(nums)")
//
insert(nums: &nums, num: 6, index: 3)
print("在索引 3 处插入数字 6 ,得到 nums = \(nums)")
//
remove(nums: &nums, index: 2)
print("删除索引 2 处的元素,得到 nums = \(nums)")
//
traverse(nums: nums)
//
let index = find(nums: nums, target: 3)
print("在 nums 中查找元素 3 ,得到索引 = \(index)")
}
}