hello-algo/codes/swift/chapter_array_and_linkedlist/array.swift
2023-08-17 05:13:19 +08:00

103 lines
2.8 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 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)")
}
}