Simplify kotlin code and improve code readability (#1198)

* Add kotlin code block for chapter_hashing

* Add kotlin code block for chapter_heap.

* Add kotlin code block for chapter_stack_and_queue and chapter_tree

* fix indentation

* Update binary_tree.md

* style(kotlin): simplify code and improve readability.

* simplify kt code for chapter_computational_complexity.

* style(kotlin): replace ArrayList with MutableList.

* Update subset_sum_i.kt

Use kotlin api instead of java.

* Update subset_sum_ii.kt

use kotlin api instead of java

* style(kotlin): replace ArrayList with mutablelist.

---------

Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
curtishd
2024-04-07 01:31:58 +08:00
committed by GitHub
parent 931d8f5089
commit 2655a2f66a
17 changed files with 101 additions and 101 deletions

View File

@ -55,7 +55,7 @@ fun traverse(nums: IntArray) {
count += nums[i]
}
// 直接遍历数组元素
for (j: Int in nums) {
for (j in nums) {
count += j
}
}
@ -63,7 +63,8 @@ fun traverse(nums: IntArray) {
/* 在数组中查找指定元素 */
fun find(nums: IntArray, target: Int): Int {
for (i in nums.indices) {
if (nums[i] == target) return i
if (nums[i] == target)
return i
}
return -1
}

View File

@ -9,7 +9,7 @@ package chapter_array_and_linkedlist
import utils.ListNode
import utils.printLinkedList
/* 在链表的节点 n0 之后插入节点p */
/* 在链表的节点 n0 之后插入节点 P */
fun insert(n0: ListNode?, p: ListNode?) {
val n1 = n0?.next
p?.next = n1
@ -18,16 +18,20 @@ fun insert(n0: ListNode?, p: ListNode?) {
/* 删除链表的节点 n0 之后的首个节点 */
fun remove(n0: ListNode?) {
val p = n0?.next
if (n0?.next == null)
return
val p = n0.next
val n1 = p?.next
n0?.next = n1
n0.next = n1
}
/* 访问链表中索引为 index 的节点 */
fun access(head: ListNode?, index: Int): ListNode? {
var h = head
for (i in 0..<index) {
h = h?.next
if (h == null)
return null
h = h.next
}
return h
}
@ -37,7 +41,8 @@ fun find(head: ListNode?, target: Int): Int {
var index = 0
var h = head
while (h != null) {
if (h.value == target) return index
if (h.value == target)
return index
h = h.next
index++
}
@ -46,6 +51,7 @@ fun find(head: ListNode?, target: Int): Int {
/* Driver Code */
fun main() {
/* 初始化链表 */
// 初始化各个节点
val n0 = ListNode(1)
val n1 = ListNode(3)
@ -60,7 +66,8 @@ fun main() {
n3.next = n4
println("初始化的链表为")
printLinkedList(n0)
/* 插入节点 */
insert(n0, ListNode(0))
println("插入节点后的链表为")
printLinkedList(n0)

View File

@ -8,9 +8,9 @@ package chapter_array_and_linkedlist
/* Driver Code */
fun main() {
/* 初始化列表 */
// 可变集合
val numbers = mutableListOf(1, 3, 2, 5, 4)
val nums = ArrayList<Int>(numbers)
val nums = mutableListOf(1, 3, 2, 5, 4)
println("列表 nums = $nums")
/* 访问元素 */
@ -53,11 +53,11 @@ fun main() {
}
/* 拼接两个列表*/
val nums1 = ArrayList<Int>(listOf(6, 8, 7, 10, 9))
val nums1 = mutableListOf(6, 8, 7, 10, 9)
nums.addAll(nums1)
println("将列表 nums1 拼接到 nums 之后,得到 nums = $nums")
/* 排序列表 */
nums.sort() //排序后,列表元素从小到大排列
nums.sort()
println("排序列表后 nums = $nums")
}

View File

@ -9,11 +9,11 @@ package chapter_array_and_linkedlist
/* 列表类 */
class MyList {
private var arr: IntArray = intArrayOf() // 数组(存储列表元素)
private var capacity = 10 // 列表容量
private var size = 0 // 列表长度(当前元素数量)
private var extendRatio = 2 // 每次列表扩容的倍数
private var capacity: Int = 10 // 列表容量
private var size: Int = 0 // 列表长度(当前元素数量)
private var extendRatio: Int = 2 // 每次列表扩容的倍数
/* 构造函数 */
/* 构造方法 */
init {
arr = IntArray(capacity)
}
@ -32,7 +32,7 @@ class MyList {
fun get(index: Int): Int {
// 索引如果越界,则抛出异常,下同
if (index < 0 || index >= size)
throw IndexOutOfBoundsException()
throw IndexOutOfBoundsException("索引越界")
return arr[index]
}
@ -72,7 +72,7 @@ class MyList {
fun remove(index: Int): Int {
if (index < 0 || index >= size)
throw IndexOutOfBoundsException("索引越界")
val num: Int = arr[index]
val num = arr[index]
// 将将索引 index 之后的元素都向前移动一位
for (j in index..<size - 1)
arr[j] = arr[j + 1]

View File

@ -10,17 +10,17 @@ package chapter_backtracking.n_queens
fun backtrack(
row: Int,
n: Int,
state: List<MutableList<String>>,
res: MutableList<List<List<String>>?>,
state: MutableList<MutableList<String>>,
res: MutableList<MutableList<MutableList<String>>?>,
cols: BooleanArray,
diags1: BooleanArray,
diags2: BooleanArray
) {
// 当放置完所有行时,记录解
if (row == n) {
val copyState: MutableList<List<String>> = ArrayList()
val copyState = mutableListOf<MutableList<String>>()
for (sRow in state) {
copyState.add(ArrayList(sRow))
copyState.add(sRow.toMutableList())
}
res.add(copyState)
return
@ -49,11 +49,11 @@ fun backtrack(
}
/* 求解 n 皇后 */
fun nQueens(n: Int): List<List<List<String>>?> {
fun nQueens(n: Int): MutableList<MutableList<MutableList<String>>?> {
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
val state: MutableList<MutableList<String>> = ArrayList()
val state = mutableListOf<MutableList<String>>()
for (i in 0..<n) {
val row: MutableList<String> = ArrayList()
val row = mutableListOf<String>()
for (j in 0..<n) {
row.add("#")
}
@ -62,7 +62,7 @@ fun nQueens(n: Int): List<List<List<String>>?> {
val cols = BooleanArray(n) // 记录列是否有皇后
val diags1 = BooleanArray(2 * n - 1) // 记录主对角线上是否有皇后
val diags2 = BooleanArray(2 * n - 1) // 记录次对角线上是否有皇后
val res: MutableList<List<List<String>>?> = ArrayList()
val res = mutableListOf<MutableList<MutableList<String>>?>()
backtrack(0, n, state, res, cols, diags1, diags2)
@ -72,7 +72,7 @@ fun nQueens(n: Int): List<List<List<String>>?> {
/* Driver Code */
fun main() {
val n = 4
val res: List<List<List<String?>?>?> = nQueens(n)
val res = nQueens(n)
println("输入棋盘长宽为 $n")
println("皇后放置方案共有 ${res.size}")

View File

@ -11,11 +11,11 @@ fun backtrack(
state: MutableList<Int>,
choices: IntArray,
selected: BooleanArray,
res: MutableList<List<Int>?>
res: MutableList<MutableList<Int>?>
) {
// 当状态长度等于元素数量时,记录解
if (state.size == choices.size) {
res.add(ArrayList(state))
res.add(state.toMutableList())
return
}
// 遍历所有选择
@ -36,9 +36,9 @@ fun backtrack(
}
/* 全排列 I */
fun permutationsI(nums: IntArray): List<List<Int>?> {
val res: MutableList<List<Int>?> = ArrayList()
backtrack(ArrayList(), nums, BooleanArray(nums.size), res)
fun permutationsI(nums: IntArray): MutableList<MutableList<Int>?> {
val res = mutableListOf<MutableList<Int>?>()
backtrack(mutableListOf(), nums, BooleanArray(nums.size), res)
return res
}

View File

@ -15,11 +15,11 @@ fun backtrack(
) {
// 当状态长度等于元素数量时,记录解
if (state.size == choices.size) {
res.add(ArrayList(state))
res.add(state.toMutableList())
return
}
// 遍历所有选择
val duplicated: MutableSet<Int> = HashSet()
val duplicated = HashSet<Int>()
for (i in choices.indices) {
val choice = choices[i]
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
@ -39,15 +39,14 @@ fun backtrack(
/* 全排列 II */
fun permutationsII(nums: IntArray): MutableList<MutableList<Int>?> {
val res: MutableList<MutableList<Int>?> = ArrayList()
backtrack(ArrayList(), nums, BooleanArray(nums.size), res)
val res = mutableListOf<MutableList<Int>?>()
backtrack(mutableListOf(), nums, BooleanArray(nums.size), res)
return res
}
/* Driver Code */
fun main() {
val nums = intArrayOf(1, 2, 2)
val res = permutationsII(nums)
println("输入数组 nums = ${nums.contentToString()}")

View File

@ -31,12 +31,12 @@ fun main() {
printTree(root)
// 前序遍历
res = ArrayList()
res = mutableListOf()
preOrder(root)
println("\n输出所有值为 7 的节点")
val vals: MutableList<Int> = ArrayList()
for (node in res as ArrayList<TreeNode>) {
val vals = mutableListOf<Int>()
for (node in res!!) {
vals.add(node.value)
}
println(vals)

View File

@ -10,7 +10,7 @@ import utils.TreeNode
import utils.printTree
var path: MutableList<TreeNode>? = null
var res: MutableList<List<TreeNode>>? = null
var res: MutableList<MutableList<TreeNode>>? = null
/* 前序遍历:例题二 */
fun preOrder(root: TreeNode?) {
@ -21,7 +21,7 @@ fun preOrder(root: TreeNode?) {
path!!.add(root)
if (root.value == 7) {
// 记录解
res!!.add(ArrayList(path!!))
res!!.add(path!!.toMutableList())
}
preOrder(root.left)
preOrder(root.right)
@ -36,13 +36,13 @@ fun main() {
printTree(root)
// 前序遍历
path = java.util.ArrayList<TreeNode>()
res = java.util.ArrayList<List<TreeNode>>()
path = mutableListOf()
res = mutableListOf()
preOrder(root)
println("\n输出所有根节点到节点 7 的路径")
for (path in res as ArrayList<List<TreeNode>>) {
val values: MutableList<Int> = ArrayList()
for (path in res!!) {
val values = mutableListOf<Int>()
for (node in path) {
values.add(node.value)
}

View File

@ -10,7 +10,7 @@ import utils.TreeNode
import utils.printTree
var path: MutableList<TreeNode>? = null
var res: MutableList<List<TreeNode>>? = null
var res: MutableList<MutableList<TreeNode>>? = null
/* 前序遍历:例题三 */
fun preOrder(root: TreeNode?) {
@ -22,7 +22,7 @@ fun preOrder(root: TreeNode?) {
path!!.add(root)
if (root.value == 7) {
// 记录解
res!!.add(ArrayList(path!!))
res!!.add(path!!.toMutableList())
}
preOrder(root.left)
preOrder(root.right)
@ -37,13 +37,13 @@ fun main() {
printTree(root)
// 前序遍历
path = ArrayList()
res = ArrayList()
path = mutableListOf()
res = mutableListOf()
preOrder(root)
println("\n输出所有根节点到节点 7 的路径,路径中不包含值为 3 的节点")
for (path in res as ArrayList<List<TreeNode>>) {
val values: MutableList<Int> = ArrayList()
for (path in res!!) {
val values = mutableListOf<Int>()
for (node in path) {
values.add(node.value)
}

View File

@ -8,20 +8,19 @@ package chapter_backtracking.preorder_traversal_iii_template
import utils.TreeNode
import utils.printTree
import java.util.*
/* 判断当前状态是否为解 */
fun isSolution(state: List<TreeNode?>): Boolean {
fun isSolution(state: MutableList<TreeNode?>): Boolean {
return state.isNotEmpty() && state[state.size - 1]?.value == 7
}
/* 记录解 */
fun recordSolution(state: MutableList<TreeNode?>?, res: MutableList<List<TreeNode?>?>) {
res.add(state?.let { ArrayList(it) })
fun recordSolution(state: MutableList<TreeNode?>?, res: MutableList<MutableList<TreeNode?>?>) {
res.add(state!!.toMutableList())
}
/* 判断在当前状态下,该选择是否合法 */
fun isValid(state: List<TreeNode?>?, choice: TreeNode?): Boolean {
fun isValid(state: MutableList<TreeNode?>?, choice: TreeNode?): Boolean {
return choice != null && choice.value != 3
}
@ -38,8 +37,8 @@ fun undoChoice(state: MutableList<TreeNode?>, choice: TreeNode?) {
/* 回溯算法:例题三 */
fun backtrack(
state: MutableList<TreeNode?>,
choices: List<TreeNode?>,
res: MutableList<List<TreeNode?>?>
choices: MutableList<TreeNode?>,
res: MutableList<MutableList<TreeNode?>?>
) {
// 检查是否为解
if (isSolution(state)) {
@ -53,7 +52,7 @@ fun backtrack(
// 尝试:做出选择,更新状态
makeChoice(state, choice)
// 进行下一轮选择
backtrack(state, listOf(choice!!.left, choice.right), res)
backtrack(state, mutableListOf(choice!!.left, choice.right), res)
// 回退:撤销选择,恢复到之前的状态
undoChoice(state, choice)
}
@ -67,12 +66,12 @@ fun main() {
printTree(root)
// 回溯算法
val res: MutableList<List<TreeNode?>?> = ArrayList()
backtrack(ArrayList(), mutableListOf(root), res)
val res = mutableListOf<MutableList<TreeNode?>?>()
backtrack(mutableListOf(), mutableListOf(root), res)
println("\n输出所有根节点到节点 7 的路径,要求路径中不包含值为 3 的节点")
for (path in res) {
val vals = ArrayList<Int>()
val vals = mutableListOf<Int>()
for (node in path!!) {
if (node != null) {
vals.add(node.value)

View File

@ -6,19 +6,17 @@
package chapter_backtracking.subset_sum_i
import java.util.*
/* 回溯算法:子集和 I */
fun backtrack(
state: MutableList<Int>,
target: Int,
choices: IntArray,
start: Int,
res: MutableList<List<Int>?>
res: MutableList<MutableList<Int>?>
) {
// 子集和等于 target 时,记录解
if (target == 0) {
res.add(ArrayList(state))
res.add(state.toMutableList())
return
}
// 遍历所有选择
@ -39,11 +37,11 @@ fun backtrack(
}
/* 求解子集和 I */
fun subsetSumI(nums: IntArray, target: Int): List<List<Int>?> {
val state: MutableList<Int> = ArrayList() // 状态(子集)
Arrays.sort(nums) // 对 nums 进行排序
fun subsetSumI(nums: IntArray, target: Int): MutableList<MutableList<Int>?> {
val state = mutableListOf<Int>() // 状态(子集)
nums.sort() // 对 nums 进行排序
val start = 0 // 遍历起始点
val res: MutableList<List<Int>?> = ArrayList() // 结果列表(子集列表)
val res = mutableListOf<MutableList<Int>?>() // 结果列表(子集列表)
backtrack(state, target, nums, start, res)
return res
}
@ -57,4 +55,4 @@ fun main() {
println("输入数组 nums = ${nums.contentToString()}, target = $target")
println("所有和等于 $target 的子集 res = $res")
}
}

View File

@ -12,11 +12,11 @@ fun backtrack(
target: Int,
total: Int,
choices: IntArray,
res: MutableList<List<Int>?>
res: MutableList<MutableList<Int>?>
) {
// 子集和等于 target 时,记录解
if (total == target) {
res.add(ArrayList(state))
res.add(state.toMutableList())
return
}
// 遍历所有选择
@ -35,10 +35,10 @@ fun backtrack(
}
/* 求解子集和 I包含重复子集 */
fun subsetSumINaive(nums: IntArray, target: Int): List<List<Int>?> {
val state: MutableList<Int> = ArrayList() // 状态(子集)
fun subsetSumINaive(nums: IntArray, target: Int): MutableList<MutableList<Int>?> {
val state = mutableListOf<Int>() // 状态(子集)
val total = 0 // 子集和
val res: MutableList<List<Int>?> = ArrayList() // 结果列表(子集列表)
val res = mutableListOf<MutableList<Int>?>() // 结果列表(子集列表)
backtrack(state, target, total, nums, res)
return res
}
@ -47,8 +47,7 @@ fun subsetSumINaive(nums: IntArray, target: Int): List<List<Int>?> {
fun main() {
val nums = intArrayOf(3, 4, 5)
val target = 9
val res: List<List<Int>?> = subsetSumINaive(nums, target)
val res = subsetSumINaive(nums, target)
println("输入数组 nums = ${nums.contentToString()}, target = $target")
println("所有和等于 $target 的子集 res = $res")

View File

@ -6,19 +6,17 @@
package chapter_backtracking.subset_sum_ii
import java.util.*
/* 回溯算法:子集和 II */
fun backtrack(
state: MutableList<Int>,
target: Int,
choices: IntArray,
start: Int,
res: MutableList<List<Int>?>
res: MutableList<MutableList<Int>?>
) {
// 子集和等于 target 时,记录解
if (target == 0) {
res.add(ArrayList(state))
res.add(state.toMutableList())
return
}
// 遍历所有选择
@ -44,11 +42,11 @@ fun backtrack(
}
/* 求解子集和 II */
fun subsetSumII(nums: IntArray, target: Int): List<List<Int>?> {
val state: MutableList<Int> = ArrayList() // 状态(子集)
Arrays.sort(nums) // 对 nums 进行排序
fun subsetSumII(nums: IntArray, target: Int): MutableList<MutableList<Int>?> {
val state = mutableListOf<Int>() // 状态(子集)
nums.sort() // 对 nums 进行排序
val start = 0 // 遍历起始点
val res: MutableList<List<Int>?> = ArrayList() // 结果列表(子集列表)
val res = mutableListOf<MutableList<Int>?>() // 结果列表(子集列表)
backtrack(state, target, nums, start, res)
return res
}
@ -57,9 +55,8 @@ fun subsetSumII(nums: IntArray, target: Int): List<List<Int>?> {
fun main() {
val nums = intArrayOf(4, 4, 5)
val target = 9
val res = subsetSumII(nums, target)
println("输入数组 nums = ${nums.contentToString()}, target = $target")
println("所有和等于 $target 的子集 res = $res")
}
}

View File

@ -60,9 +60,9 @@ fun linearRecur(n: Int) {
/* 平方阶 */
fun quadratic(n: Int) {
// 矩阵占用 O(n^2) 空间
val numMatrix: Array<Array<Int>?> = arrayOfNulls(n)
val numMatrix = arrayOfNulls<Array<Int>?>(n)
// 二维列表占用 O(n^2) 空间
val numList: MutableList<MutableList<Int>> = arrayListOf()
val numList = mutableListOf<MutableList<Int>>()
for (i in 0..<n) {
val tmp = mutableListOf<Int>()
for (j in 0..<n) {
@ -104,6 +104,6 @@ fun main() {
quadratic(n)
quadraticRecur(n)
// 指数阶
val root: TreeNode? = buildTree(n)
val root = buildTree(n)
printTree(root)
}

View File

@ -9,7 +9,7 @@ package chapter_computational_complexity.time_complexity
/* 常数阶 */
fun constant(n: Int): Int {
var count = 0
val size = 10_0000
val size = 100000
for (i in 0..<size)
count++
return count
@ -48,7 +48,7 @@ fun quadratic(n: Int): Int {
/* 平方阶(冒泡排序) */
fun bubbleSort(nums: IntArray): Int {
var count = 0
var count = 0 // 计数器
// 外循环:未排序区间为 [0, i]
for (i in nums.size - 1 downTo 1) {
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
@ -109,7 +109,7 @@ fun linearLogRecur(n: Int): Int {
if (n <= 1)
return 1
var count = linearLogRecur(n / 2) + linearLogRecur(n / 2)
for (i in 0..<n.toInt()) {
for (i in 0..<n) {
count++
}
return count
@ -133,7 +133,7 @@ fun main() {
val n = 8
println("输入数据大小 n = $n")
var count: Int = constant(n)
var count = constant(n)
println("常数阶的操作数量 = $count")
count = linear(n)
@ -144,7 +144,8 @@ fun main() {
count = quadratic(n)
println("平方阶的操作数量 = $count")
val nums = IntArray(n)
for (i in 0..<n) nums[i] = n - i // [n,n-1,...,2,1]
for (i in 0..<n)
nums[i] = n - i // [n,n-1,...,2,1]
count = bubbleSort(nums)
println("平方阶(冒泡排序)的操作数量 = $count")

View File

@ -13,10 +13,9 @@ fun randomNumbers(n: Int): Array<Int?> {
for (i in 0..<n) {
nums[i] = i + 1
}
// 随机打乱数组元素
val mutableList = nums.toMutableList()
// 随机打乱数组元素
mutableList.shuffle()
// Integer[] -> int[]
val res = arrayOfNulls<Int>(n)
for (i in 0..<n) {
res[i] = mutableList[i]
@ -39,8 +38,8 @@ fun findOne(nums: Array<Int?>): Int {
fun main() {
for (i in 0..9) {
val n = 100
val nums: Array<Int?> = randomNumbers(n)
val index: Int = findOne(nums)
val nums = randomNumbers(n)
val index = findOne(nums)
println("\n数组 [ 1, 2, ..., n ] 被打乱后 = ${nums.contentToString()}")
println("数字 1 的索引为 $index")
}