Improve readability of Kotlin code (#1236)

* style(kotlin): Improve kotlin codes readability.

* remove redundant quotes.

* style(kotlin): improve codes readability.
This commit is contained in:
curtishd 2024-04-08 16:09:34 +08:00 committed by GitHub
parent ba1df4a3e8
commit 3fe8f67ba9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
12 changed files with 46 additions and 51 deletions

View File

@ -6,8 +6,6 @@
package chapter_greedy package chapter_greedy
import java.util.*
/* 物品 */ /* 物品 */
class Item( class Item(
val w: Int, // 物品 val w: Int, // 物品
@ -15,25 +13,21 @@ class Item(
) )
/* 分数背包:贪心 */ /* 分数背包:贪心 */
fun fractionalKnapsack( fun fractionalKnapsack(wgt: IntArray, _val: IntArray, c: Int): Double {
wgt: IntArray,
value: IntArray,
c: Int
): Double {
// 创建物品列表,包含两个属性:重量、价值 // 创建物品列表,包含两个属性:重量、价值
var cap = c var cap = c
val items = arrayOfNulls<Item>(wgt.size) val items = arrayOfNulls<Item>(wgt.size)
for (i in wgt.indices) { for (i in wgt.indices) {
items[i] = Item(wgt[i], value[i]) items[i] = Item(wgt[i], _val[i])
} }
// 按照单位价值 item.v / item.w 从高到低进行排序 // 按照单位价值 item.v / item.w 从高到低进行排序
Arrays.sort(items, Comparator.comparingDouble { item: Item -> -(item.v.toDouble() / item.w) }) items.sortBy { item: Item? -> -(item!!.v.toDouble() / item.w) }
// 循环贪心选择 // 循环贪心选择
var res = 0.0 var res = 0.0
for (item in items) { for (item in items) {
if (item!!.w <= cap) { if (item!!.w <= cap) {
// 若剩余容量充足,则将当前物品整个装进背包 // 若剩余容量充足,则将当前物品整个装进背包
res += item.v.toDouble() res += item.v
cap -= item.w cap -= item.w
} else { } else {
// 若剩余容量不足,则将当前物品的一部分装进背包 // 若剩余容量不足,则将当前物品的一部分装进背包

View File

@ -19,8 +19,8 @@ fun maxCapacity(ht: IntArray): Int {
// 循环贪心选择,直至两板相遇 // 循环贪心选择,直至两板相遇
while (i < j) { while (i < j) {
// 更新最大容量 // 更新最大容量
val cap = (min(ht[i].toDouble(), ht[j].toDouble()) * (j - i)).toInt() val cap = min(ht[i], ht[j]) * (j - i)
res = max(res.toDouble(), cap.toDouble()).toInt() res = max(res, cap)
// 向内移动短板 // 向内移动短板
if (ht[i] < ht[j]) { if (ht[i] < ht[j]) {
i++ i++

View File

@ -19,14 +19,14 @@ fun maxProductCutting(n: Int): Int {
val b = n % 3 val b = n % 3
if (b == 1) { if (b == 1) {
// 当余数为 1 时,将一对 1 * 3 转化为 2 * 2 // 当余数为 1 时,将一对 1 * 3 转化为 2 * 2
return 3.0.pow((a - 1).toDouble()).toInt() * 2 * 2 return 3.0.pow((a - 1)).toInt() * 2 * 2
} }
if (b == 2) { if (b == 2) {
// 当余数为 2 时,不做处理 // 当余数为 2 时,不做处理
return 3.0.pow(a.toDouble()).toInt() * 2 * 2 return 3.0.pow(a).toInt() * 2 * 2
} }
// 当余数为 0 时,不做处理 // 当余数为 0 时,不做处理
return 3.0.pow(a.toDouble()).toInt() return 3.0.pow(a).toInt()
} }
/* Driver Code */ /* Driver Code */

View File

@ -14,14 +14,8 @@ class Pair(
/* 基于数组实现的哈希表 */ /* 基于数组实现的哈希表 */
class ArrayHashMap { class ArrayHashMap {
private val buckets = arrayOfNulls<Pair>(100)
init {
// 初始化数组,包含 100 个桶 // 初始化数组,包含 100 个桶
for (i in 0..<100) { private val buckets = arrayOfNulls<Pair>(100)
buckets[i] = null
}
}
/* 哈希函数 */ /* 哈希函数 */
fun hashFunc(key: Int): Int { fun hashFunc(key: Int): Int {
@ -52,25 +46,27 @@ class ArrayHashMap {
/* 获取所有键值对 */ /* 获取所有键值对 */
fun pairSet(): MutableList<Pair> { fun pairSet(): MutableList<Pair> {
val pairSet = ArrayList<Pair>() val pairSet = mutableListOf<Pair>()
for (pair in buckets) { for (pair in buckets) {
if (pair != null) pairSet.add(pair) if (pair != null)
pairSet.add(pair)
} }
return pairSet return pairSet
} }
/* 获取所有键 */ /* 获取所有键 */
fun keySet(): MutableList<Int> { fun keySet(): MutableList<Int> {
val keySet = ArrayList<Int>() val keySet = mutableListOf<Int>()
for (pair in buckets) { for (pair in buckets) {
if (pair != null) keySet.add(pair.key) if (pair != null)
keySet.add(pair.key)
} }
return keySet return keySet
} }
/* 获取所有值 */ /* 获取所有值 */
fun valueSet(): MutableList<String> { fun valueSet(): MutableList<String> {
val valueSet = ArrayList<String>() val valueSet = mutableListOf<String>()
for (pair in buckets) { for (pair in buckets) {
pair?.let { valueSet.add(it.value) } pair?.let { valueSet.add(it.value) }
} }
@ -82,7 +78,7 @@ class ArrayHashMap {
for (kv in pairSet()) { for (kv in pairSet()) {
val key = kv.key val key = kv.key
val value = kv.value val value = kv.value
println("${key}->${value}") println("${key} -> ${value}")
} }
} }
} }
@ -104,7 +100,7 @@ fun main() {
/* 查询操作 */ /* 查询操作 */
// 向哈希表中输入键 key ,得到值 value // 向哈希表中输入键 key ,得到值 value
val name: String? = map.get(15937) val name = map.get(15937)
println("\n输入学号 15937 ,查询到姓名 $name") println("\n输入学号 15937 ,查询到姓名 $name")
/* 删除操作 */ /* 删除操作 */
@ -114,7 +110,7 @@ fun main() {
map.print() map.print()
/* 遍历哈希表 */ /* 遍历哈希表 */
println("\n遍历键值对 Key->Value") println("\n遍历键值对 Key -> Value")
for (kv in map.pairSet()) { for (kv in map.pairSet()) {
println("${kv.key} -> ${kv.value}") println("${kv.key} -> ${kv.value}")
} }

View File

@ -11,15 +11,15 @@ import utils.ListNode
/* Driver Code */ /* Driver Code */
fun main() { fun main() {
val num = 3 val num = 3
val hashNum = Integer.hashCode(num) val hashNum = num.hashCode()
println("整数 $num 的哈希值为 $hashNum") println("整数 $num 的哈希值为 $hashNum")
val bol = true val bol = true
val hashBol = Boolean.hashCode() val hashBol = bol.hashCode()
println("布尔量 $bol 的哈希值为 $hashBol") println("布尔量 $bol 的哈希值为 $hashBol")
val dec = 3.14159 val dec = 3.14159
val hashDec = java.lang.Double.hashCode(dec) val hashDec = dec.hashCode()
println("小数 $dec 的哈希值为 $hashDec") println("小数 $dec 的哈希值为 $hashDec")
val str = "Hello 算法" val str = "Hello 算法"

View File

@ -11,7 +11,7 @@ import utils.printHashMap
/* Driver Code */ /* Driver Code */
fun main() { fun main() {
/* 初始化哈希表 */ /* 初始化哈希表 */
val map: MutableMap<Int, String> = HashMap() val map = HashMap<Int, String>()
/* 添加操作 */ /* 添加操作 */
// 在哈希表中添加键值对 (key, value) // 在哈希表中添加键值对 (key, value)

View File

@ -20,7 +20,7 @@ class HashMapChaining() {
capacity = 4 capacity = 4
loadThres = 2.0 / 3.0 loadThres = 2.0 / 3.0
extendRatio = 2 extendRatio = 2
buckets = ArrayList(capacity) buckets = mutableListOf()
for (i in 0..<capacity) { for (i in 0..<capacity) {
buckets.add(mutableListOf()) buckets.add(mutableListOf())
} }

View File

@ -8,16 +8,21 @@ package chapter_hashing
/* 开放寻址哈希表 */ /* 开放寻址哈希表 */
class HashMapOpenAddressing { class HashMapOpenAddressing {
private var size: Int = 0 // 键值对数量 private var size: Int // 键值对数量
private var capacity = 4 // 哈希表容量 private var capacity: Int // 哈希表容量
private val loadThres: Double = 2.0 / 3.0 // 触发扩容的负载因子阈值 private val loadThres: Double // 触发扩容的负载因子阈值
private val extendRatio = 2 // 扩容倍数 private val extendRatio: Int // 扩容倍数
private var buckets: Array<Pair?> // 桶数组 private var buckets: Array<Pair?> // 桶数组
private val TOMBSTONE = Pair(-1, "-1") // 删除标记 private val TOMBSTONE: Pair // 删除标记
/* 构造方法 */ /* 构造方法 */
init { init {
size = 0
capacity = 4
loadThres = 2.0 / 3.0
extendRatio = 2
buckets = arrayOfNulls(capacity) buckets = arrayOfNulls(capacity)
TOMBSTONE = Pair(-1, "-1")
} }
/* 哈希函数 */ /* 哈希函数 */

View File

@ -6,7 +6,7 @@
package chapter_hashing package chapter_hashing
const val MODULUS = 10_0000_0007 const val MODULUS = 1000000007
/* 加法哈希 */ /* 加法哈希 */
fun addHash(key: String): Int { fun addHash(key: String): Int {
@ -48,7 +48,7 @@ fun rotHash(key: String): Int {
fun main() { fun main() {
val key = "Hello 算法" val key = "Hello 算法"
var hash: Int = addHash(key) var hash = addHash(key)
println("加法哈希值为 $hash") println("加法哈希值为 $hash")
hash = mulHash(key) hash = mulHash(key)

View File

@ -25,7 +25,7 @@ fun testPop(heap: Queue<Int>) {
fun main() { fun main() {
/* 初始化堆 */ /* 初始化堆 */
// 初始化小顶堆 // 初始化小顶堆
val minHeap: PriorityQueue<Int> var minHeap = PriorityQueue<Int>()
// 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可) // 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可)
val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } val maxHeap = PriorityQueue { a: Int, b: Int -> b - a }

View File

@ -10,13 +10,14 @@ import utils.printHeap
import java.util.* import java.util.*
/* 大顶堆 */ /* 大顶堆 */
class MaxHeap(nums: List<Int>?) { class MaxHeap(nums: MutableList<Int>?) {
// 使用列表而非数组,这样无须考虑扩容问题 // 使用列表而非数组,这样无须考虑扩容问题
// 将列表元素原封不动添加进堆 private val maxHeap = mutableListOf<Int>()
private val maxHeap = ArrayList(nums!!)
/* 构造函数,根据输入列表建堆 */ /* 构造方法,根据输入列表建堆 */
init { init {
// 将列表元素原封不动添加进堆
maxHeap.addAll(nums!!)
// 堆化除叶节点以外的其他所有节点 // 堆化除叶节点以外的其他所有节点
for (i in parent(size() - 1) downTo 0) { for (i in parent(size() - 1) downTo 0) {
siftDown(i) siftDown(i)

View File

@ -7,7 +7,6 @@
package chapter_searching package chapter_searching
import utils.ListNode import utils.ListNode
import java.util.HashMap
/* 哈希查找(数组) */ /* 哈希查找(数组) */
fun hashingSearchArray(map: Map<Int?, Int>, target: Int): Int { fun hashingSearchArray(map: Map<Int?, Int>, target: Int): Int {