You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/codes/swift/chapter_array_and_linkedlist/array.swift

108 lines
2.8 KiB

/**
* 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
}
//
for (i, num) in nums.enumerated() {
count += nums[i]
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)")
}
}