Refine kotlin code (#1241)

* style(kotlin): Improve kotlin codes readability.

* remove redundant quotes.

* style(kotlin): improve codes readability.

* style(kotlin): refine kotlin codes.

* Create kotlin.yml

* Create kotlin.yml

* Delete .github/workflows/kotlin

* Delete .github/workflows/main.yml

* Create kotlin.yml

* Update kotlin.yml

* Delete .github/workflows/kotlin.yml

* Create hello_world_workflow.main.kts

* Delete .github/workflows/hello_world_workflow.main.kts

* remove empty line
This commit is contained in:
curtishd 2024-04-09 16:26:58 +08:00 committed by GitHub
parent 41dd677338
commit 896d9a64f6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
22 changed files with 158 additions and 112 deletions

View File

@ -14,7 +14,7 @@ fun bubbleSort(nums: IntArray) {
for (j in 0..<i) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]
nums[j] = nums[j+1].also { nums[j+1] = nums[j] }
nums[j] = nums[j + 1].also { nums[j + 1] = nums[j] }
}
}
}

View File

@ -6,15 +6,13 @@
package chapter_sorting
import kotlin.collections.ArrayList
/* 桶排序 */
fun bucketSort(nums: FloatArray) {
// 初始化 k = n/2 个桶,预期向每个桶分配 2 个元素
val k = nums.size / 2
val buckets = ArrayList<ArrayList<Float>>()
val buckets = mutableListOf<MutableList<Float>>()
for (i in 0..<k) {
buckets.add(ArrayList())
buckets.add(mutableListOf())
}
// 1. 将数组元素分配到各个桶中
for (num in nums) {

View File

@ -14,7 +14,7 @@ fun countingSortNaive(nums: IntArray) {
// 1. 统计数组最大元素 m
var m = 0
for (num in nums) {
m = max(m.toDouble(), num.toDouble()).toInt()
m = max(m, num)
}
// 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数
@ -40,7 +40,7 @@ fun countingSort(nums: IntArray) {
// 1. 统计数组最大元素 m
var m = 0
for (num in nums) {
m = max(m.toDouble(), num.toDouble()).toInt()
m = max(m, num)
}
// 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数

View File

@ -14,10 +14,13 @@ fun siftDown(nums: IntArray, n: Int, li: Int) {
val l = 2 * i + 1
val r = 2 * i + 2
var ma = i
if (l < n && nums[l] > nums[ma]) ma = l
if (r < n && nums[r] > nums[ma]) ma = r
if (l < n && nums[l] > nums[ma])
ma = l
if (r < n && nums[r] > nums[ma])
ma = r
// 若节点 i 最大或索引 l, r 越界,则无须继续堆化,跳出
if (ma == i) break
if (ma == i)
break
// 交换两节点
nums[i] = nums[ma].also { nums[ma] = nums[i] }
// 循环向下堆化

View File

@ -12,7 +12,7 @@ fun insertionSort(nums: IntArray) {
for (i in nums.indices) {
val base = nums[i]
var j = i - 1
// 内循环: 将 base 插入到已排序部分的正确位置
// 内循环:将 base 插入到已排序区间 [0, i-1] 中的正确位置
while (j >= 0 && nums[j] > base) {
nums[j + 1] = nums[j] // 将 nums[j] 向右移动一位
j--

View File

@ -17,8 +17,10 @@ fun merge(nums: IntArray, left: Int, mid: Int, right: Int) {
var k = 0
// 当左右子数组都还有元素时,进行比较并将较小的元素复制到临时数组中
while (i <= mid && j <= right) {
if (nums[i] <= nums[j]) tmp[k++] = nums[i++]
else tmp[k++] = nums[j++]
if (nums[i] <= nums[j])
tmp[k++] = nums[i++]
else
tmp[k++] = nums[j++]
}
// 将左子数组和右子数组的剩余元素复制到临时数组中
while (i <= mid) {

View File

@ -35,7 +35,8 @@ fun countingSortDigit(nums: IntArray, exp: Int) {
counter[d]-- // 将 d 的数量减 1
}
// 使用结果覆盖原数组 nums
for (i in 0..<n) nums[i] = res[i]
for (i in 0..<n)
nums[i] = res[i]
}
/* 基数排序 */

View File

@ -14,7 +14,8 @@ fun selectionSort(nums: IntArray) {
var k = i
// 内循环:找到未排序区间内的最小元素
for (j in i + 1..<n) {
if (nums[j] < nums[k]) k = j // 记录最小元素的索引
if (nums[j] < nums[k])
k = j // 记录最小元素的索引
}
// 将该最小元素与未排序区间的首个元素交换
nums[i] = nums[k].also { nums[k] = nums[i] }

View File

@ -7,10 +7,11 @@
package chapter_stack_and_queue
/* 基于环形数组实现的双向队列 */
/* 构造方法 */
class ArrayDeque(capacity: Int) {
private var nums = IntArray(capacity) // 用于存储双向队列元素的数组
private var front = 0 // 队首指针,指向队首元素
private var queSize = 0 // 双向队列长度
private var nums: IntArray = IntArray(capacity) // 用于存储双向队列元素的数组
private var front: Int = 0 // 队首指针,指向队首元素
private var queSize: Int = 0 // 双向队列长度
/* 获取双向队列的容量 */
fun capacity(): Int {
@ -71,7 +72,7 @@ class ArrayDeque(capacity: Int) {
return num
}
/* 访问队尾元素 */
/* 队尾出队 */
fun popLast(): Int {
val num = peekLast()
queSize--

View File

@ -8,9 +8,9 @@ package chapter_stack_and_queue
/* 基于环形数组实现的队列 */
class ArrayQueue(capacity: Int) {
private val nums = IntArray(capacity) // 用于存储队列元素的数组
private var front = 0 // 队首指针,指向队首元素
private var queSize = 0 // 队列长度
private val nums: IntArray = IntArray(capacity) // 用于存储队列元素的数组
private var front: Int = 0 // 队首指针,指向队首元素
private var queSize: Int = 0 // 队列长度
/* 获取队列的容量 */
fun capacity(): Int {

View File

@ -9,7 +9,7 @@ package chapter_stack_and_queue
/* 基于数组实现的栈 */
class ArrayStack {
// 初始化列表(动态数组)
private val stack = ArrayList<Int>()
private val stack = mutableListOf<Int>()
/* 获取栈的长度 */
fun size(): Int {
@ -40,7 +40,7 @@ class ArrayStack {
/* 将 List 转化为 Array 并返回 */
fun toArray(): Array<Any> {
return stack.toArray()
return stack.toTypedArray()
}
}
@ -63,7 +63,7 @@ fun main() {
/* 元素出栈 */
val pop = stack.pop()
println("出栈元素 pop = ${pop},出栈后 stack = ${stack.toArray().contentToString()}")
println("出栈元素 pop = $pop,出栈后 stack = ${stack.toArray().contentToString()}")
/* 获取栈的长度 */
val size = stack.size()

View File

@ -7,7 +7,7 @@
package chapter_stack_and_queue
/* 双向链表节点 */
class ListNode(var value: Int) {
class ListNode(var _val: Int) {
// 节点值
var next: ListNode? = null // 后继节点引用
var prev: ListNode? = null // 前驱节点引用
@ -15,9 +15,9 @@ class ListNode(var value: Int) {
/* 基于双向链表实现的双向队列 */
class LinkedListDeque {
private var front: ListNode? = null // 头节点 front ,尾节点 rear
private var rear: ListNode? = null
private var queSize = 0 // 双向队列的长度
private var front: ListNode? = null // 头节点 front
private var rear: ListNode? = null // 尾节点 rear
private var queSize: Int = 0 // 双向队列的长度
/* 获取双向队列的长度 */
fun size(): Int {
@ -64,12 +64,12 @@ class LinkedListDeque {
/* 出队操作 */
fun pop(isFront: Boolean): Int {
if (isEmpty()) throw IndexOutOfBoundsException()
if (isEmpty())
throw IndexOutOfBoundsException()
val value: Int
// 队首出队操作
if (isFront) {
value = front!!.value // 暂存头节点值
value = front!!._val // 暂存头节点值
// 删除头节点
val fNext = front!!.next
if (fNext != null) {
@ -79,7 +79,7 @@ class LinkedListDeque {
front = fNext // 更新头节点
// 队尾出队操作
} else {
value = rear!!.value // 暂存尾节点值
value = rear!!._val // 暂存尾节点值
// 删除尾节点
val rPrev = rear!!.prev
if (rPrev != null) {
@ -104,17 +104,14 @@ class LinkedListDeque {
/* 访问队首元素 */
fun peekFirst(): Int {
if (isEmpty()) {
throw IndexOutOfBoundsException()
}
return front!!.value
if (isEmpty()) throw IndexOutOfBoundsException()
return front!!._val
}
/* 访问队尾元素 */
fun peekLast(): Int {
if (isEmpty()) throw IndexOutOfBoundsException()
return rear!!.value
return rear!!._val
}
/* 返回数组用于打印 */
@ -122,7 +119,7 @@ class LinkedListDeque {
var node = front
val res = IntArray(size())
for (i in res.indices) {
res[i] = node!!.value
res[i] = node!!._val
node = node.next
}
return res

View File

@ -52,7 +52,7 @@ class LinkedListQueue(
/* 访问队首元素 */
fun peek(): Int {
if (isEmpty()) throw IndexOutOfBoundsException()
return front!!.value
return front!!._val
}
/* 将链表转化为 Array 并返回 */
@ -60,7 +60,7 @@ class LinkedListQueue(
var node = front
val res = IntArray(size())
for (i in res.indices) {
res[i] = node!!.value
res[i] = node!!._val
node = node.next
}
return res

View File

@ -41,7 +41,7 @@ class LinkedListStack(
/* 访问栈顶元素 */
fun peek(): Int? {
if (isEmpty()) throw IndexOutOfBoundsException()
return stackPeek?.value
return stackPeek?._val
}
/* 将 List 转化为 Array 并返回 */
@ -49,7 +49,7 @@ class LinkedListStack(
var node = stackPeek
val res = IntArray(size())
for (i in res.size - 1 downTo 0) {
res[i] = node?.value!!
res[i] = node?._val!!
node = node.next
}
return res

View File

@ -10,7 +10,8 @@ import utils.TreeNode
import utils.printTree
/* 数组表示下的二叉树类 */
class ArrayBinaryTree(private val tree: List<Int?>) {
/* 构造方法 */
class ArrayBinaryTree(private val tree: MutableList<Int?>) {
/* 列表容量 */
fun size(): Int {
return tree.size
@ -39,11 +40,12 @@ class ArrayBinaryTree(private val tree: List<Int?>) {
}
/* 层序遍历 */
fun levelOrder(): List<Int?> {
val res = ArrayList<Int?>()
fun levelOrder(): MutableList<Int?> {
val res = mutableListOf<Int?>()
// 直接遍历数组
for (i in 0..<size()) {
if (value(i) != null) res.add(value(i))
if (value(i) != null)
res.add(value(i))
}
return res
}
@ -51,34 +53,38 @@ class ArrayBinaryTree(private val tree: List<Int?>) {
/* 深度优先遍历 */
fun dfs(i: Int, order: String, res: MutableList<Int?>) {
// 若为空位,则返回
if (value(i) == null) return
if (value(i) == null)
return
// 前序遍历
if ("pre" == order) res.add(value(i))
if ("pre" == order)
res.add(value(i))
dfs(left(i), order, res)
// 中序遍历
if ("in" == order) res.add(value(i))
if ("in" == order)
res.add(value(i))
dfs(right(i), order, res)
// 后序遍历
if ("post" == order) res.add(value(i))
if ("post" == order)
res.add(value(i))
}
/* 前序遍历 */
fun preOrder(): List<Int?> {
val res = ArrayList<Int?>()
fun preOrder(): MutableList<Int?> {
val res = mutableListOf<Int?>()
dfs(0, "pre", res)
return res
}
/* 中序遍历 */
fun inOrder(): List<Int?> {
val res = ArrayList<Int?>()
fun inOrder(): MutableList<Int?> {
val res = mutableListOf<Int?>()
dfs(0, "in", res)
return res
}
/* 后序遍历 */
fun postOrder(): List<Int?> {
val res = ArrayList<Int?>()
fun postOrder(): MutableList<Int?> {
val res = mutableListOf<Int?>()
dfs(0, "post", res)
return res
}

View File

@ -23,7 +23,7 @@ class AVLTree {
/* 更新节点高度 */
private fun updateHeight(node: TreeNode?) {
// 节点高度等于最高子树高度 + 1
node?.height = (max(height(node?.left).toDouble(), height(node?.right).toDouble()) + 1).toInt()
node?.height = max(height(node?.left), height(node?.right)) + 1
}
/* 获取平衡因子 */
@ -103,10 +103,12 @@ class AVLTree {
return TreeNode(value)
var node = n
/* 1. 查找插入位置并插入节点 */
if (value < node.value) node.left = insertHelper(node.left, value)
else if (value > node.value) node.right = insertHelper(node.right, value)
else return node // 重复节点不插入,直接返回
if (value < node.value)
node.left = insertHelper(node.left, value)
else if (value > node.value)
node.right = insertHelper(node.right, value)
else
return node // 重复节点不插入,直接返回
updateHeight(node) // 更新节点高度
/* 2. 执行旋转操作,使该子树重新恢复平衡 */
node = rotate(node)
@ -123,14 +125,22 @@ class AVLTree {
private fun removeHelper(n: TreeNode?, value: Int): TreeNode? {
var node = n ?: return null
/* 1. 查找节点并删除 */
if (value < node.value) node.left = removeHelper(node.left, value)
else if (value > node.value) node.right = removeHelper(node.right, value)
if (value < node.value)
node.left = removeHelper(node.left, value)
else if (value > node.value)
node.right = removeHelper(node.right, value)
else {
if (node.left == null || node.right == null) {
val child = if (node.left != null) node.left else node.right
val child = if (node.left != null)
node.left
else
node.right
// 子节点数量 = 0 ,直接删除 node 并返回
if (child == null) return null
else node = child
if (child == null)
return null
// 子节点数量 = 1 ,直接删除 node
else
node = child
} else {
// 子节点数量 = 2 ,则将中序遍历的下个节点删除,并用该节点替换当前节点
var temp = node.right
@ -154,9 +164,14 @@ class AVLTree {
// 循环查找,越过叶节点后跳出
while (cur != null) {
// 目标节点在 cur 的右子树中
cur = if (cur.value < value) cur.right!!
else (if (cur.value > value) cur.left
else break)!!
cur = if (cur.value < value)
cur.right!!
// 目标节点在 cur 的左子树中
else if (cur.value > value)
cur.left
// 找到目标节点,跳出循环
else
break
}
// 返回目标节点
return cur

View File

@ -11,6 +11,7 @@ import utils.printTree
/* 二叉搜索树 */
class BinarySearchTree {
// 初始化空树
private var root: TreeNode? = null
/* 获取二叉树根节点 */
@ -24,11 +25,14 @@ class BinarySearchTree {
// 循环查找,越过叶节点后跳出
while (cur != null) {
// 目标节点在 cur 的右子树中
cur = if (cur.value < num) cur.right
cur = if (cur.value < num)
cur.right
// 目标节点在 cur 的左子树中
else if (cur.value > num) cur.left
else if (cur.value > num)
cur.left
// 找到目标节点,跳出循环
else break
else
break
}
// 返回目标节点
return cur
@ -46,45 +50,60 @@ class BinarySearchTree {
// 循环查找,越过叶节点后跳出
while (cur != null) {
// 找到重复节点,直接返回
if (cur.value == num) return
if (cur.value == num)
return
pre = cur
// 插入位置在 cur 的右子树中
cur = if (cur.value < num) cur.right
cur = if (cur.value < num)
cur.right
// 插入位置在 cur 的左子树中
else cur.left
else
cur.left
}
// 插入节点
val node = TreeNode(num)
if (pre?.value!! < num) pre.right = node
else pre.left = node
if (pre?.value!! < num)
pre.right = node
else
pre.left = node
}
/* 删除节点 */
fun remove(num: Int) {
// 若树为空,直接提前返回
if (root == null) return
if (root == null)
return
var cur = root
var pre: TreeNode? = null
// 循环查找,越过叶节点后跳出
while (cur != null) {
// 找到待删除节点,跳出循环
if (cur.value == num) break
if (cur.value == num)
break
pre = cur
// 待删除节点在 cur 的右子树中
cur = if (cur.value < num) cur.right
cur = if (cur.value < num)
cur.right
// 待删除节点在 cur 的左子树中
else cur.left
else
cur.left
}
// 若无待删除节点,则直接返回
if (cur == null) return
if (cur == null)
return
// 子节点数量 = 0 or 1
if (cur.left == null || cur.right == null) {
// 当子节点数量 = 0 / 1 时, child = null / 该子节点
val child = if (cur.left != null) cur.left else cur.right
val child = if (cur.left != null)
cur.left
else
cur.right
// 删除节点 cur
if (cur != root) {
if (pre!!.left == cur) pre.left = child
else pre.right = child
if (pre!!.left == cur)
pre.left = child
else
pre.right = child
} else {
// 若删除节点为根节点,则重新指定根节点
root = child

View File

@ -16,13 +16,14 @@ fun levelOrder(root: TreeNode?): MutableList<Int> {
val queue = LinkedList<TreeNode?>()
queue.add(root)
// 初始化一个列表,用于保存遍历序列
val list = ArrayList<Int>()
while (!queue.isEmpty()) {
val list = mutableListOf<Int>()
while (queue.isNotEmpty()) {
val node = queue.poll() // 队列出队
list.add(node?.value!!) // 保存节点值
if (node.left != null) queue.offer(node.left) // 左子节点入队
if (node.right != null) queue.offer(node.right) // 右子节点入队
if (node.left != null)
queue.offer(node.left) // 左子节点入队
if (node.right != null)
queue.offer(node.right) // 右子节点入队
}
return list
}

View File

@ -10,7 +10,7 @@ import utils.TreeNode
import utils.printTree
// 初始化列表,用于存储遍历序列
var list = ArrayList<Int>()
var list = mutableListOf<Int>()
/* 前序遍历 */
fun preOrder(root: TreeNode?) {

View File

@ -20,7 +20,7 @@ fun <T> printMatrix(matrix: Array<Array<T>>) {
}
/* 打印矩阵List */
fun <T> printMatrix(matrix: List<List<T>>) {
fun <T> printMatrix(matrix: MutableList<MutableList<T>>) {
println("[")
for (row in matrix) {
println(" $row,")
@ -31,7 +31,7 @@ fun <T> printMatrix(matrix: List<List<T>>) {
/* 打印链表 */
fun printLinkedList(h: ListNode?) {
var head = h
val list = ArrayList<String>()
val list = mutableListOf<String>()
while (head != null) {
list.add(head.value.toString())
head = head.next
@ -91,16 +91,17 @@ fun showTrunks(p: Trunk?) {
/* 打印哈希表 */
fun <K, V> printHashMap(map: Map<K, V>) {
for ((key, value) in map) {
println(key.toString() + " -> " + value)
println("${key.toString()} -> $value")
}
}
/* 打印堆 */
fun printHeap(queue: Queue<Int>?) {
val list = queue?.let { ArrayList(it) }
val list = mutableListOf<Int?>()
queue?.let { list.addAll(it) }
print("堆的数组表示:")
println(list)
println("堆的树状表示:")
val root = list?.let { TreeNode.listToTree(it) }
val root = TreeNode.listToTree(list)
printTree(root)
}

View File

@ -7,6 +7,7 @@
package utils
/* 二叉树节点类 */
/* 构造方法 */
class TreeNode(
var value: Int // 节点值
) {
@ -59,8 +60,8 @@ class TreeNode(
}
/* 将二叉树序列化为列表 */
fun treeToList(root: TreeNode?): List<Int?> {
val res = ArrayList<Int?>()
fun treeToList(root: TreeNode?): MutableList<Int?> {
val res = mutableListOf<Int?>()
treeToListDFS(root, 0, res)
return res
}

View File

@ -19,8 +19,8 @@ class Vertex(val value: Int) {
}
/* 输入顶点列表 vets ,返回值列表 vals */
fun vetsToVals(vets: List<Vertex?>): List<Int> {
val vals = ArrayList<Int>()
fun vetsToVals(vets: MutableList<Vertex?>): MutableList<Int> {
val vals = mutableListOf<Int>()
for (vet in vets) {
vals.add(vet!!.value)
}