hello-algo/codes/swift/chapter_array_and_linkedlist/array.swift
Yudong Jin e720aa2d24
feat: Revised the book (#978)
* Sync recent changes to the revised Word.

* Revised the preface chapter

* Revised the introduction chapter

* Revised the computation complexity chapter

* Revised the chapter data structure

* Revised the chapter array and linked list

* Revised the chapter stack and queue

* Revised the chapter hashing

* Revised the chapter tree

* Revised the chapter heap

* Revised the chapter graph

* Revised the chapter searching

* Reivised the sorting chapter

* Revised the divide and conquer chapter

* Revised the chapter backtacking

* Revised the DP chapter

* Revised the greedy chapter

* Revised the appendix chapter

* Revised the preface chapter doubly

* Revised the figures
2023-12-02 06:21:34 +08:00

102 lines
2.7 KiB
Swift

/**
* 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 nums.indices.dropFirst(index).reversed() {
nums[i] = nums[i - 1]
}
// num index
nums[index] = num
}
/* index */
func remove(nums: inout [Int], index: Int) {
// index
for i in nums.indices.dropFirst(index).dropLast() {
nums[i] = nums[i + 1]
}
}
/* */
func traverse(nums: [Int]) {
var count = 0
//
for i in nums.indices {
count += nums[i]
}
//
for num in nums {
count += num
}
}
/* */
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)")
}
}